启用“颜色混合图层”时,是否可以将非英文字符的UILabel设为绿色?

我有一个自定义单元格的表视图,我尝试通过在模拟器中选中Color Blended Layer时使单元格内的所有子视图都为绿色来优化它。

当单元格中UILabel的背景设置为白色时:

 let title = UILabel() contentView.addSubview(title) title.background = UIColor.whiteColor() title.text = "Hi, how are you?" 

这个UILabel子视图在模拟器中会变成绿色,这很好。 但是,如果我将文本更改为某些中文:

 title.text = "你好" 

UILabel子视图将变为红色。 这篇SOpost提供了一些关于这种情况的解释。 实际上有解决方案吗?

使用CATextLayer而不是UILabel 。 并且不要忘记将其opaque属性设置为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:如果黑色背景不是你想要的,问题会变得有点棘手,但还是可以解决的。

您只需要在绘图机制中注入两行代码。 有两种方法可以实现这一目标:

  • 使用CALayerdelegate

  • 创建CATextLayer的子类。

在我们的例子中,我认为后者更可取。 因此,在下面的示例中使用此类而不是CATextLayer

 class OpaqueTextLayerWithCustomizableBackgroundColor: CATextLayer { override func drawInContext(ctx: CGContext) { if let color = backgroundColor { CGContextSetFillColorWithColor(ctx, color) CGContextFillRect(ctx, bounds); } super.drawInContext(ctx) } } 

仅供参考,XIB(个人偏好)或代码中的三个步骤。

  1. 设置opaque = YES
  2. backgroundColor =纯色
  3. clipsToBound = YES

然后非英语UILabel将渲染 – 传递一次,为绿色。

我不得不说这是Apple的内部实现。 我们不应该/(可能)不能摆弄它。 毕竟,您看到的“颜色”只是图层结构的表示。 你附上的问题的答案是一个很好的解释。

我建议不要计划任何过早的优化。 毕竟,即使您确实感觉到性能提升,“颜色混合层”也很难看,无法应用于真实设备。 或者只是尽量不去关注它!

编辑:

这是来自Apple模拟器的屏幕截图,如果Apple可以使用它,你也可以忍受它! 在此处输入图像描述

您可以使用旧样式执行此操作,并手动重新着色:

 for (CALayer *sublayer in label.layer.sublayers) { //possibly add an if check here for a layer that actually renders text, it may be the case, that you don't want to color one of them sublayer.backgroundColor = label.backgroundColor; } 

每次iOS实际刷新颜色时你可能必须这样做,它可能永远不会,它可能在每个layoutSubviews 。 你必须尝试一下对你有用的东西。 如果这是一个单元格,那么在prepareForReuse可能是安全的。 如果这对性能影响太大,请尝试使用initawakeFromNib并依靠Apple自行更改。

检查你的textlayer.string首字母是英文还是其他字母

  NSMutableArray*arrAlphabets; arrAlphabets=[NSMutableArray arrayWithObjects:@"A", @"B", @"C", @"D", @"E", @"F", @"G", @"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z",nil]] 

然后在Indexpath方法的内部Tableview单元格中行:

 NSString *str=[textlayer.string substringToIndex:1]; if(str isEqualToString:arrAlphabets) //use for loop to run arralphabets { //do your code to maintail the layer color . } 

希望这个概念可以帮助你:)

也许您可以根据使用的字体检查等宽字符(西方)与比例字符(中文)。

等宽字符是8位,其中比例1是16位。 我不知道Swift如何检查字节大小,所以我无法提供任何代码。

Apple的Swift编程指南可以提供帮助。 查看标题为:字符串的Unicode表示的部分。