【问题标题】:numberOfLines in UILabel is not woking after use NSMutableAttributedString使用 NSMutableAttributedString 后,UILabel 中的 numberOfLines 无法正常工作
【发布时间】:2019-11-04 10:23:05
【问题描述】:

我在 UILabel 中做多色文本。它运作良好。但问题是我明白了,我可以在 UIlabel 中显示多行。这意味着 numberOfLine 属性不起作用。

     extension NSMutableAttributedString {

     func setColorForText(textForAttribute: String, withColor color: UIColor) {
        let range: NSRange = self.mutableString.range(of: textForAttribute, options: .caseInsensitive)
        self.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)

    }




         let stringValue = "Natural air is most important part of human body. people got too much problem because of it. please everybody try to do best part for it"


        let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: stringValue)
        attributedString.setColorForText(textForAttribute: "\(item.catName ?? "")", withColor: Colors.green)

        postInfoLabel.font = UIFont.systemFont(ofSize: ViewSize.width/33)
       postInfoLabel.numberOfLines = 0
           postInfoLabel.attributedText = attributedString

【问题讨论】:

  • numberOfLines = 0 表示任意行数。
  • 所以你想在一个标签中显示多行文本但你只有一个?
  • 我使用 numberOfLines = 0。字符串应该显示为两行或三行。但它只显示一行
  • bazyli7 是对的。你是对的朋友。 bazyl87
  • 检查您是否对标签应用了适当的约束?

标签: ios swift string colors uilabel


【解决方案1】:

用于包装和截断标签文本的技术是根据您的用例将 lineBreakMode 属性值设置为 NSLineBreakByWordWrapping 或 NSLineBreakByTruncatingTail。当您将 UILabel 的 numberOfLines 属性设置为 0 时,这应该对您有用。

【讨论】:

    【解决方案2】:

    numberOfLines 不是一个函数,而是一个属性,它指示UILabel 应该显示多少行。如果您将此值设置为0,您将告诉 label 根据需要使用尽可能多的行来显示文本。您可以在numberOfLines documentation 阅读更多详细信息。

    我不太确定你想通过将字体大小设置为ViewSize.width/33 来实现什么,可能存在问题(比如 ViewSize 计算不正确)。您能否更详细地解释您想要实现什么,以及您将获得什么?

    【讨论】:

    • ViewSize.width = self.view.frame.size.width
    • 但是如果你在viewDidLoad中使用,则可能无法设置视图框架@
    猜你喜欢
    • 1970-01-01
    • 2014-11-15
    • 2013-12-01
    • 2015-07-13
    • 1970-01-01
    • 2016-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多