ios - 使用 addSublayer() 添加 CATextLayer

标签 ios iphone swift xcode layer

我写这段代码:

let myAttributes = [
    NSAttributedStringKey.font: UIFont(name: "Avenir-HeavyOblique", size: 15.0)! ,
    NSAttributedStringKey.foregroundColor: UIColor.white
]
let myAttributedString = NSAttributedString(string: textRightUpLabel!, attributes: myAttributes )
let textLayer = CATextLayer()
textLayer.string = myAttributedString
textLayer.backgroundColor = UIColor.clear.cgColor
textLayer.frame = CGRect(x: self.frame.size.width - width + textMarginRightUpLabel, y: 8, width: width, height: height)
self.layer.addSublayer(textLayer)

这很好用,但它似乎增加了 2 层如何在我的 Storyboard中显示它:

storyboard image

所以问题是:为什么文本“3 DAYS LEFT”显示了 2 次?一个在好的地方,另一个在 ShapeLayer 后面?

感谢您的回复

最佳答案

将 texlayer 变量移出该函数并使其成为 View 的变量。

let textLayer = CATextLayer()

将它添加到层的位置检查并查看层是否已经包含这样的 textLayer,而不是一遍又一遍地添加它。抱歉,这在手机上有点乱。当我回到我的 Mac 时会检查并清理它。

if let subLs = self.sublayers, subLs.contains(textLayer) == true{//do nothing
 }else{
      self.layer.addSublayer(textLayer)
  }

关于ios - 使用 addSublayer() 添加 CATextLayer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51304387/

相关文章:

ios - TwitterKit 没有控制重定向到 native Twitter 应用程序的接口(interface)

ios - 删除核心数据项

当从链接安装应用程序时,iOS 应用程序传递特定的 ID

ios - 监控 CBPeripheral 状态变化

ios - 在后台调用 ios 应用程序并在应用程序关闭或终止时执行运行一些代码

ios - 如何检查屏幕上是否显示 View ? (Swift 5 和 SwiftUI)

ios - Segue 反推效应

iphone - EXC_BAD_ACCESS 带有 characterAtIndex,但不是 substringToIndex

iphone - 使用 alassestsLibrary 时出错

iphone - 如何在当前时间添加时间