Swift截断标签替代文本

时间:2017-09-19 10:43:37

标签: swift swift3 label uilabel truncation

我在水平堆栈视图控制器中有两个标签:

labelA.text = "This is text number A"
labelB.text = "This is text number B"

他们被截断了:

[This is... This is...]

有没有办法为标签提供替代文本,以便显示它是否会截断原始文本,例如

labelA.alternateText = "A"
labelB.alternateText = "B"

所以显示

[A B ]

但如果可以

,仍会显示两个标签的全文

1 个答案:

答案 0 :(得分:3)

你可以这样做:

1:添加扩展名以检查您的标签是否被截断

extension UILabel {
    var isTruncated: Bool {
        guard let labelText = text else {
            return false
        }
        let labelTextSize = (labelText as NSString).boundingRect(
            with: CGSize(width: frame.size.width, height: .greatestFiniteMagnitude),
            options: .usesLineFragmentOrigin,
            attributes: [NSFontAttributeName: font],
            context: nil).size

        return labelTextSize.height > bounds.size.height
    }
}

2:添加字典以存储原始字符串

var dict = [Int:Any]()

3:添加标签时,为它们添加标签(代表密钥)

let label = UILabel(frame: CGRect(x: 0, y: 0, width: 30, height: 50))
label.text = "This is text number A"
label.tag = 0

4:检查标签是否被截断,如果是,则添加默认值并将原始值存储到dict中:

if label.isTruncated {
    dict.updateValue(label.text, forKey: label.tag)
    label.text = "A"
}

5:取回原始值

let original = dict[0] // for tag 0 for example