简体   繁体   English

如何截断UILabel以在字符串末尾显示“…”

[英]How to truncate UILabel to show '…' at the end of the string

I have a UILabel() i am trying to truncate. 我有一个UILabel()正在尝试截断。

    let nameLabel: UILabel = {
        let label = UILabel()
        label.textColor = .black
        label.translatesAutoresizingMaskIntoConstraints = false
        label.font = UIFont.systemFont(ofSize: 11)
        label.numberOfLines = 0
        //label.lineBreakMode = .byTruncatingTail
        //label.adjustsFontSizeToFitWidth = false
        label.textAlignment = .center
        label.sizeToFit()

        return label
    }()

here are my constraints: 这是我的约束:

    nameLabel.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
    nameLabel.widthAnchor.constraint(equalTo: self.widthAnchor, constant: -10).isActive = true
    nameLabel.topAnchor.constraint(equalTo: profileImageView.bottomAnchor, constant: 8).isActive = true

The issue that i am having is that the actual string gets truncated but instead of having the string 'Johnson Rodriguez' truncate to ' 'Johnson Rod...' ' it ends up cropping out anything after the space, resulting in the label displaying 'Johnson' 我遇到的问题是实际的字符串被截断了,但是没有将字符串'Johnson Rodriguez'截断为' 'Johnson Rod...' ',它最终在空格后裁剪掉了所有内容,导致标签显示为'Johnson'

These are the things i have tried using: 这些是我尝试使用的东西:

    label.lineBreakMode = .byTruncatingTail 
    label.sizeToFit()
    label.preferredMaxLayoutWidth = 70

This is what i have seen other people use but for some reason i cant get it to display the ... instead of truncating the string at the first space. 这是我看到的其他人使用的东西,但是由于某种原因,我无法让它显示...而不是在第一个空格处截断字符串。

Setting numberOfLines to 1 should do the trick for you. numberOfLines设置为1应该可以解决问题。

From the docs: 从文档:

This property controls the maximum number of lines to use in order to fit the label's text into its bounding rectangle. 此属性控制为了使标签文本适合其边界矩形而使用的最大行数。 The default value for this property is 1. To remove any maximum limit, and use as many lines as needed, set the value of this property to 0. 此属性的默认值为1。要删除任何最大限​​制,并根据需要使用任意多的行,请将此属性的值设置为0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM