问题甚至出现在情节提要中。
UILabel具有以下属性:
如您所见,第四个单词不适合第一行,因此会因布局错误而出现问题。如果我删除了最后一个单词,则句子完全适合一行,或者说第四个单词。如果在添加单词后将它们都移动到下一行,则会留出很多空间。它应该尽可能地使单词适合而不会在一行中出现断字或连字符。但是即使单词可以容纳,也显然会留出空白。
您可以在新项目中重新创建它,然后观察问题。
答案 0 :(得分:2)
您可能想尝试一下...
子类UITextView
,禁用滚动,编辑和选择...,将textContainerInset = UIEdgeInsets.zero
和textContainer.lineFragmentPadding = 0
设置为零。
结果:
代码(@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])
}
}