numberOfLines不起作用

时间:2018-05-31 09:26:55

标签: ios swift uilabel

这是我的代码,而不是使用numberOfLines。 我该如何解决呢?

let texts = UILabel()
texts.frame.size.width = 100
texts.text = "fehjafiuehfoaijeoijaoifjajfeiojfoiafeafelfhlkfesjahflkejshflesjfheakjfehlfkjehalkfh"
texts.lineBreakMode = .byWordWrapping
texts.numberOfLines = 2
texts.font = UIFont.systemFont(ofSize: 15, weight: .light)
texts.backgroundColor = UIColor.clear
let DetailSpaceStyle = NSMutableParagraphStyle()
DetailSpaceStyle.lineSpacing = 6.0
let detailSpaceAttr = [NSAttributedStringKey.paragraphStyle: DetailSpaceStyle]
texts.attributedText = NSMutableAttributedString(string: texts.text!, attributes: detailSpaceAttr)
texts.sizeToFit()

2 个答案:

答案 0 :(得分:0)

您需要指定UILabel身高

texts.frame.size.height = 100

并且您需要按照CGRect

的说明将UILabel设置为@Anbu.karthik
    let texts = UILabel()
    texts.frame.origin.x = 5
    texts.frame.origin.y = 5
    texts.frame.size.width = 100
    texts.frame.size.height = 100
    texts.text = "fehjafiuehfoaijeoijaoifjajfeiojfoiafeafelfhlkfesjahflkejshflesjfheakjfehlfkjehalkfh"
    texts.lineBreakMode = .byTruncatingTail
    texts.numberOfLines = 2
    texts.font = UIFont.systemFont(ofSize: 15, weight: .light)
    texts.backgroundColor = UIColor.clear
    let DetailSpaceStyle = NSMutableParagraphStyle()
    DetailSpaceStyle.lineSpacing = 6.0
    let detailSpaceAttr = [NSAttributedStringKey.paragraphStyle: DetailSpaceStyle]
    texts.attributedText = NSMutableAttributedString(string: texts.text!, attributes: detailSpaceAttr)
    texts.sizeToFit()
    self.view.addSubview(texts)

答案 1 :(得分:0)

如果你想在最后一个单词上添加“...”,你应该使用

texts.lineBreakMode = .byTruncatingTail 代替 texts.lineBreakMode = .byWordWrapping

仅当文本的长度超过您为其提供的两行的空间时才会出现