Use 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:如果黑色背景不是您想要的,问题就会变得有点棘手,但仍然可以解决。
您所需要的只是将两行代码注入到绘图机制中。有两种方法可以实现此目的:
就我们而言,我认为后者更可取。所以而不是CATextLayer
在下面的示例中使用此类:
class OpaqueTextLayerWithCustomizableBackgroundColor: CATextLayer {
override func drawInContext(ctx: CGContext) {
if let color = backgroundColor {
CGContextSetFillColorWithColor(ctx, color)
CGContextFillRect(ctx, bounds);
}
super.drawInContext(ctx)
}
}