swift - 如何在 UILabel 文本中添加空白

标签 swift text uilabel whitespace

我想在 UILabel 的任何给定文本前面添加一个空格。

我认为我可以按如下方式扩展 UILabel 类:

class UILabel_iKK: UILabel {

    override var text: String? {
        didSet {
            if let txt = self.text {
                self.text = " " + txt
            }
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

但显然这会导致无限循环(即文本更改导致 didSet 一次又一次触发。

以最优雅的方式做到这一点的另一种方式是什么?

最佳答案

是的,这是可能的。尽管我不喜欢它,但以下代码不会永远循环:

didSet {
  if let txt = self.text, txt.first != " " {
    self.text = " " + txt
  }
}

关于swift - 如何在 UILabel 文本中添加空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47908698/

相关文章:

css - 划掉文本 CSS

ios - 将多个 UILabels 居中放置在一行上

swift - 在 swift 4.1 中使用 nil 合并进行隐式解包时出现意外的 "some()"

swift - 如何从 IOS 客户端连接到 Spring WebSocket 服务器?

python - 我可以在文本小部件内创建跨多行的 Tkinter Canvas 吗?

ios - 为什么我的 UITextField 委托(delegate)方法没有被调用?

iphone - 将标签的文本用于变量,以便稍后在 iOS5 中使用

ios - UILabel 无法正确更新

ios - Firebase 图像上传进度屏幕指示器 -Swift iOS

ios - 将新的 plist 文件添加到 iOS 应用程序