【发布时间】:2020-10-19 13:00:40
【问题描述】:
我在 tableview 单元格中的内容视图的 stackview 中有一个 UILabel。一切正常,单元格正在调整大小,但我无法将 UILabel 中的文本居中。我总是在文本底部有奇怪的空格。查看屏幕截图。
黄色:内容视图 绿色:堆栈视图 蓝色:标签
其他信息:单元格没有静态高度。黄色视图具有顶部底部和尾随和前导约束以及水平和垂直对齐到超级视图与堆栈视图相同的东西。我通过代码激活和停用的唯一具有恒定高度的是按钮。所以它根据单元格隐藏和显示。 Stackview 按比例填充。
UILabel 是 sizeToFit
也试过了:
detailLbl.textAlignment = .center
detailLbl.lineBreakMode = .byWordWrapping //also tried byClipping
detailLbl.baselineAdjustment = .alignCenters
我将里面的文本解析为 HTML
"<p><font color=\"#cd1719\">V/. </font>…The Word of the Lord.<br><b></b><font color=\"#cd1719\">R/. </font><b>Thanks be to God.</b></p>"
第二张截图
"<h6 lang=\"en\" style=\"color=#cd1719 !important; font-weight: normal !important\"><font color=\"#cd1719\" weight=\"normal\"><i>The alleluia is said or sung.</i></font></h6>"
这是我用来解析 HTML 的 NSAttributedString 扩展
extension NSAttributedString {
convenience init(htmlString html: String, font: UIFont? = nil, useDocumentFontSize: Bool = true) throws {
let options: [NSAttributedString.DocumentReadingOptionKey : Any] = [
.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: String.Encoding.utf8.rawValue
]
let data = html.data(using: .utf8, allowLossyConversion: true)
guard (data != nil), let fontFamily = font?.familyName, let attr = try? NSMutableAttributedString(data: data!, options: options, documentAttributes: nil) else {
try self.init(data: data ?? Data(html.utf8), options: options, documentAttributes: nil)
return
}
let fontSize: CGFloat? = useDocumentFontSize ? nil : font!.pointSize
let range = NSRange(location: 0, length: attr.length)
attr.enumerateAttribute(.font, in: range, options: .longestEffectiveRangeNotRequired) { attrib, range, _ in
if let htmlFont = attrib as? UIFont {
let traits = htmlFont.fontDescriptor.symbolicTraits
var descrip = htmlFont.fontDescriptor.withFamily(fontFamily)
if (traits.rawValue & UIFontDescriptor.SymbolicTraits.traitBold.rawValue) != 0 {
descrip = descrip.withSymbolicTraits(.traitBold)!
}
if (traits.rawValue & UIFontDescriptor.SymbolicTraits.traitItalic.rawValue) != 0 {
descrip = descrip.withSymbolicTraits(.traitItalic)!
}
attr.addAttribute(.font, value: UIFont(descriptor: descrip, size: fontSize ?? htmlFont.pointSize), range: range)
}
}
self.init(attributedString: attr)
}
}
这就是我在代码中使用它的方式
if let attributedString = try? NSAttributedString(htmlString: htmlTxt, font: UIFont(name: "Avenir-Roman", size: CGFloat(Constants.defualtContentDescriptionFontSize)), useDocumentFontSize: false) {
cell.detailLbl.attributedText = attributedString
}
【问题讨论】:
-
显示约束代码?你为桌子设置了静态高度吗?
-
@Sh_Khan 没有静态高度。黄色视图具有顶部底部和尾随和前导约束以及水平和垂直对齐到超级视图与堆栈视图相同的东西。我通过代码激活和停用的唯一具有恒定高度的是按钮。所以它根据单元格隐藏和显示。 Stackview 按比例填充
-
@KeghamK。 - 不要使用按比例填充...使用
Fill。不要更改按钮的高度限制。设置按钮的.isHidden属性以显示/隐藏它。隐藏时,堆栈视图将自动删除它所占用的空间。 -
@DonMag 也试过了,但它没有用。是的,无需更改隐藏的约束就足够了,但底部仍然有这个空间
-
@KeghamK。 - 显示您用于解析 html 的代码。尝试在主视图中仅使用
UILabel开始 - 忘记将其嵌入到表格视图单元格的堆栈视图中。
标签: swift uitableview uilabel uistackview