UILabel text truncation vs. line breaks in text

前端 未结 2 1911
深忆病人
深忆病人 2020-12-04 03:24

I have a UILabel that is put as titleView in the navigation bar. I want it to have 2 lines, where the first line can be truncated and the second is center align

相关标签:
2条回答
  • 2020-12-04 04:04

    change your line breakmode to ByTruncatingMiddle instead of ByTruncatingTail. Something like below,

        label.lineBreakMode = .ByTruncatingMiddle
    

    Hope this will help :)

    0 讨论(0)
  • 2020-12-04 04:14

    Navigation Tittle with sub-Tittle (Multiline Navigation Tittle)

    Use NSMutableAttributedString with UITextView instead of UILabel

    (because, if tittle is large then UILabel lineBreakMode with .byTruncatingTail is not working for first line in UILabel)

    func multilineNavigation(title:String,subTitle:String) {
    
        DispatchQueue.main.async {
            let titleAttributedStr = NSMutableAttributedString(string: title, attributes: [NSAttributedStringKey.foregroundColor: UIColor.orange,NSAttributedStringKey.font: UIFont(name: "Helvetica Neue", size: 17.0) ?? UIFont()])
            let subTitleAttributedStr = NSMutableAttributedString(string: "\n\(subTitle)", attributes: [NSAttributedStringKey.foregroundColor: UIColor.green,NSAttributedStringKey.font: UIFont(name: "Helvetica Neue", size: 12.0) ?? UIFont()])
            titleAttributedStr.append(subTitleAttributedStr)
    
            let paragraphStyle = NSMutableParagraphStyle()
            paragraphStyle.lineSpacing = 1
            paragraphStyle.lineBreakMode = .byTruncatingTail
    
            titleAttributedStr.addAttribute(.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, titleAttributedStr.length))
    
            let textView = UITextView()
            textView.attributedText = titleAttributedStr
            textView.backgroundColor = .clear
            textView.isUserInteractionEnabled = false
            textView.textContainerInset = .zero
            textView.textAlignment = .center
            textView.frame = CGRect(x: 0, y: 0, width: textView.intrinsicContentSize.width, height: 44)
    
            self.navigationItem.titleView = textView
        }
    }
    
    0 讨论(0)
提交回复
热议问题