【问题标题】:CATextLayer cannot align to center horizontally with UILabel text in swiftCATextLayer 无法在 swift 中与 UILabel 文本水平对齐
【发布时间】:2020-06-03 14:15:45
【问题描述】:

当我在 swift 5 中使用 CATextLayer 时,我使用水平对齐模式将其对齐到中心,遵循 here 但它不能对齐到中心。这是我的一些代码

myLabel.textAlignment = .center

textLayer.frame = myLabel.bounds;
textLayer.alignmentMode = CATextLayerAlignmentMode.center

但是当我在 ipad pro 上运行时,我将位置 x 设置为 500 并且它移动到了中心

textLayer.position = CGPoint(500,20)

但这并不准确,我不知道为什么会这样。那么如何将 CATextLayer 与中心对齐作为中心标签文本呢?

【问题讨论】:

  • 什么是 textLayer ?
  • textLayer 是 CATextLayer 的一个对象。 var textLayer:CATextLayer = CATextLayer() textLayer.frame = myLabel.bounds; textLayer.alignmentMode = CATextLayerAlignmentMode.center ... cell.myLabel!.layer.addSubLayer(textLayer)
  • 你什么时候设置.frame和/或.position?如果自动布局尚未完成工作,则可能尚未设置框架和边界。
  • 感谢@DonMag。我会再检查一次!

标签: ios swift catextlayer


【解决方案1】:

我不知道您的代码中的 textLayer 是什么,但如果您想使用 CATextLayerAlignmentMode,您可以将其设置为您的标签

  myLabel.textAlignment = CATextLayerAlignmentMode.center

【讨论】:

  • 无法将“CATextLayerAlignmentMode”类型的值分配给“NSTextAlignment”类型 myLabel.textAlignment 使用 NSTextAlignment,因此 myLabel.textAlignment = NSTextAlignment.center。并且... textLayer.alignmentMode = CATextLayerAlignmentMode.center
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-29
  • 2021-02-03
  • 2011-06-09
  • 2020-09-26
  • 2011-06-13
  • 1970-01-01
  • 2013-08-14
相关资源
最近更新 更多