启用“颜色混合图层”时,是否可以将非英文字符的UILabel设为绿色? [英] Is it possible to make UILabel with non-English characters green when Color Blended Layer is enabled?
问题描述
我有一个带有自定义单元格的表格视图,我尝试通过在模拟器中选中颜色混合图层
时使单元格内的所有子视图都为绿色来优化它。
I have a table view with custom cells and I try to optimize it by making all subviews inside the cells in green color when Color Blended Layer
is checked in the simulator.
当单元格中 UILabel
的背景设置为白色时:
When the background of an UILabel
in the cell is set to white:
let title = UILabel()
contentView.addSubview(title)
title.background = UIColor.whiteColor()
title.text = "Hi, how are you?"
这个UILabel子视图在模拟器中会变成绿色,这很好。但是,如果我将文本更改为中文:
This UILabel subview will become green color in the simulator, which is good. However, if I change the text to some Chinese:
title.text = "你好"
UILabel子视图将变为红色。这个 SO帖子提供了一些关于情况。实际上有解决方案吗?
The UILabel subview will become red. This SO post provides some explanation about the situation. Is there actually a solution for this?
推荐答案
使用 CATextLayer
代替 UILabel
。并且不要忘记将 opaque
属性设置为 true
。
Use CATextLayer
instead of UILabel
. And don't forget to set its opaque
property to true
.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
// You should definitely put layer handling logic into
// UITableViewCell subclass. I'm omitting it for clarity
let layer = cell.contentView.layer
let textLayer = CATextLayer()
textLayer.string = "你好"
textLayer.bounds = CGRect(x: 0, y: 0, width: 100, height: 50)
textLayer.position = CGPoint(x: 50, y: 25)
textLayer.opaque = true
layer.addSublayer(textLayer)
return cell
}
UPD:如果黑色背景不是你想要的,问题会变得有点棘手,但还是可以解决的。
UPD: If a black background is not what you are looking for, a problem becomes a bit trickier, but yet solvable.
您只需要在绘图机制中注入两行代码。有两种方法可以达到这个目的:
All you need is to inject two lines of code into drawing mechanism. There are two ways to achieve this:
-
使用
委托
CALayer
或
创建 CATextLayer $的子类C $ C>。
在我们的案例中,我认为后者更可取。因此,在下面的示例中,不使用 CATextLayer
,而是使用此类:
In our case I believe the latter is preferable. So instead of CATextLayer
in the example below use this class:
class OpaqueTextLayerWithCustomizableBackgroundColor: CATextLayer {
override func drawInContext(ctx: CGContext) {
if let color = backgroundColor {
CGContextSetFillColorWithColor(ctx, color)
CGContextFillRect(ctx, bounds);
}
super.drawInContext(ctx)
}
}
这篇关于启用“颜色混合图层”时,是否可以将非英文字符的UILabel设为绿色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!