UILabel自动换行功能可留出空间,即使该单词

时间:2019-07-03 11:42:09

标签: ios swift autolayout uikit ios-autolayout

问题甚至出现在情节提要中。

UILabel具有以下属性:

  • numberOfLines = 0
  • lineBreakMode = .byWordWrapping
  • 约束:领先和落后26分,获得超级观看;垂直居中。
  • 自定义字体:中17点。

如您所见,第四个单词不适合第一行,因此会因布局错误而出现问题。如果我删除了最后一个单词,则句子完全适合一行,或者说第四个单词。如果在添加单词后将它们都移动到下一行,则会留出很多空间。它应该尽可能地使单词适合而不会在一行中出现断字或连字符。但是即使单词可以容纳,也显然会留出空白。

您可以在新项目中重新创建它,然后观察问题。

enter image description here

2 个答案:

答案 0 :(得分:2)

您可能想尝试一下...

子类UITextView,禁用滚动,编辑和选择...,将textContainerInset = UIEdgeInsets.zerotextContainer.lineFragmentPadding = 0设置为零。

结果:

enter image description here

代码(@IBDesignable,因此我们可以在IB /情节提要中看到它):

@IBDesignable
class TextViewLabel: UITextView {

    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        commonInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    func commonInit() -> Void {
        isScrollEnabled = false
        isEditable = false
        isSelectable = false
        textContainerInset = UIEdgeInsets.zero
        textContainer.lineFragmentPadding = 0
    }

}

答案 1 :(得分:0)

此代码可以在固定宽度标签中使用,它将克服该问题, 也可以获取标签的高度

  private static func calculateLabelProperties() -> (String, CGFloat){

    let titleString = "Your string here"

        let wordArray = titleString.components(separatedBy: " ")
        var lineCount = 1//first line denoted by 1
        var tempWidth:CGFloat = 0
        var title = ""
        for (index,element) in wordArray.enumerated() {
            let width = calculateFontSize(title: element + " ", fontName: "your font name", fontSize: 17).width
            tempWidth = tempWidth + width

            //get the nextelement
            var nextElement = ""
            if wordArray.count > index + 1 {
                nextElement = wordArray[index + 1]
            }

            let nextElementWidth = calculateFontSize(title: nextElement, fontName: "your font name", fontSize: 17).width

            if tempWidth + nextElementWidth > 410 {//410 is labelwidth
                tempWidth = 0
                lineCount += 1
                title = "\(title)\(element)\n"
            } else {
                title = "\(title)\(element) "
            }
        }
        return (title, CGFloat(lineCount * 20))//20 is label sigle line height
    }

此代码计算字体大小

func calculateFontSize(title: String, fontName: String, fontSize: CGFloat) -> (width: CGFloat, height: CGFloat){
    let font = UIFont(name: fontName, size: fontSize)
    return (title.size(OfFont: font!).width, title.size(OfFont: font!).height)
}

获取字体大小

extension String {
    func size(OfFont font: UIFont) -> CGSize {
        return (self as NSString).size(withAttributes: [NSAttributedString.Key.font: font])
    }
}