自动换行不适用于UILabel

时间:2018-04-14 11:29:34

标签: ios xcode uilabel

结果,UILabel。只有在单词太长时才会发生。

enter image description here

以下是我想要实现的目标。如果我降低Lable高度,它会起作用。但标签高度是动态的

enter image description here

帮助欣赏。 谢谢

6 个答案:

答案 0 :(得分:0)

正如我发现所有lineBreakMode模式将在单词大于该行时在另一行上传递字符。 似乎修复它的唯一方法是更改​​字体大小以适应这个词。自动收缩有一些限制,并且不会检测到将单词拆分为多行,因此您需要手动检测该单词是否未适合并相应地更改字体大小。

对同一问题的提问:How to make multi-line UILabel text fit within predefined width without wrapping mid-word

答案 1 :(得分:-1)

您可以将约束设置为标签的要求。假如你不想要修复高度那么就没有必要设置底部约束。

见下图我已经为动态标签高度设置了约束。希望这会对你有所帮助。

constraint properties

答案 2 :(得分:-1)

试试这个。它应该缩小字体,以适应一行中最长的单词。如果你看到一个更好的方式让我知道,因为我希望改善这一点。我相信我可以适应它在IB工作。

import UIKit

extension UILabel{

    func adjustedFont()->UIFont {
        let attributes: [NSAttributedStringKey: Any] = [.font: font]
        let attributedString = NSAttributedString(string: text ?? "", attributes: attributes)
        let drawingContext = NSStringDrawingContext()
        drawingContext.minimumScaleFactor = minimumScaleFactor

        attributedString.boundingRect(with: bounds.integral.size,
                                      options: .usesLineFragmentOrigin,
                                      context: drawingContext)

        let fontSize = font.pointSize * drawingContext.actualScaleFactor

        return font.withSize(fontSize)
    }

    func fitMaxWord(){
        layoutIfNeeded()
        let scaledFont = self.adjustedFont()
        let currentFont = scaledFont
        if let txt = text,
            let maxString = txt.components(separatedBy: " ").max(by: {$1.count > $0.count})?.replacingOccurrences(of: "\n", with: ""){
            let maxFontSize: CGFloat = currentFont.pointSize
            let minFontSize: CGFloat = 5.0


            var q = maxFontSize
            var p = minFontSize
            let height = currentFont.lineHeight
            let constraintSize = CGSize(width: .greatestFiniteMagnitude, height: height)
            var sizedFont = currentFont
            while(p <= q){
                let currentSize = (p + q) / CGFloat(2)
                sizedFont = currentFont.withSize( CGFloat(currentSize) )

                let text = NSMutableAttributedString(string:maxString, attributes:[NSAttributedStringKey.font:sizedFont])

                let textRect = text.boundingRect(with: constraintSize, options: [.usesLineFragmentOrigin], context: nil).integral
                let labelSize = textRect.width

                //1 is a fudge factor
                if labelSize == ceil(self.bounds.width - 1){
                    break
                }else if labelSize > ceil(self.bounds.width - 1){
                    q = currentSize - 0.1
                }else{
                    p = currentSize + 0.1
                }
            }

            if sizedFont.pointSize < currentFont.pointSize{
                self.font = sizedFont
            }
        }
    }
}

最小例子:

导入UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        //we could test longer text
        //
        let text = "CHULALONGKORN UNIVERSITY Plus a lot of additional text to make sure it still does not clip a word"
        let testLabel = UILabel(frame: .zero)
        //testLabel.text = "CHULALONGKORN UNIVERSITY"
        testLabel.text = text
        testLabel.numberOfLines = 0
        testLabel.textAlignment = .center
        testLabel.font = UIFont.systemFont(ofSize: 45)
        testLabel.adjustsFontSizeToFitWidth = true //unneeded in this instance but lets set it
        testLabel.minimumScaleFactor = 0.3
        self.view.addSubview(testLabel)
        testLabel.translatesAutoresizingMaskIntoConstraints = false
        testLabel.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 20).isActive = true
        testLabel.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -20).isActive = true
        testLabel.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 50).isActive = true
        self.view.layoutIfNeeded()
        testLabel.fitMaxWord()
    }


}

ExampleImage 这应该适用于大多数情况。我测试了你的文字和更多的文字。您可以在上面的示例中看到两者。

答案 3 :(得分:-1)

如果您的字符串具有固定值,就像您在问题中显示的那样(例如CHULALONGKORN UNIVERSITY),以下是您的问题的解决方案。

在界面构建器中为标签设置以下属性。

  1. 将标签文本值设置为两行,如下面的快照所示(不是像CHULALONGKORN UNIVERSITY这样的单行)。按 alt +输入取代两个单词之间的空格。
  2. 设置行数= 2
  3. 设置换行模式= Truncate Tail
  4. 将自动收缩设置为Minimum Font Scale' and value for scale to 0.5`或您想要设置的最小比例。
  5. - enter image description here

答案 4 :(得分:-2)

你应该尝试UILabel对齐对齐enter image description here

答案 5 :(得分:-2)

每当您将标签高度设为动态

在属性检查器enter image description here

中选择计数为0

然后根据标签的内容自动增加高度。