value = UILabel(frame: CGRect(x: 5 ,y: 5, width:Int(self.view.frame.width - 140) ,height: 16 ))
value.numberOfLines = 0
value.font = UIFont.systemFont(ofSize: 14.0)
value.lineBreakMode = .byWordWrapping
value.text = ((items["comment"] as? String) ?? "")!
value.setLineHeight(lineHeight: CGFloat(1))
var lineCount = 0;
let textSize = CGSize(width: value.frame.size.width, height: CGFloat(Float.infinity));
let rHeight = lroundf(Float(value.sizeThatFits(textSize).height))
let charSize = lroundf(Float(value.font.lineHeight));
lineCount = rHeight/charSize
print(lineCount)
}
当试图获取该UILabel中的行数时。它总是给我一个实际的行数......
extension UILabel {
func setLineHeight(lineHeight: CGFloat) {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 1.0
paragraphStyle.lineHeightMultiple = lineHeight
paragraphStyle.alignment = self.textAlignment
let attrString = NSMutableAttributedString(string: self.text!)
attrString.addAttribute(NSFontAttributeName, value: self.font, range: NSMakeRange(0, attrString.length))
attrString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSMakeRange(0, attrString.length))
self.attributedText = attrString
}
}
答案 0 :(得分:0)
检查此代码。这会正确计算行数。我在XCode 8中测试了它
value = UILabel(frame: CGRect(x: 50 ,y: 50, width:Int(self.view.frame.width - 140) ,height: 400 ))
value.numberOfLines = 0
value.font = UIFont.systemFont(ofSize: 14.0)
value.lineBreakMode = .byWordWrapping
value.text = ((items["comment"] as? String) ?? "")!
let textSize = CGSize(width: value.frame.size.width, height: CGFloat(Float.infinity));
let rHeight = Float(value.sizeThatFits(textSize).height)
var lineCount:Float = 0;
let charSize = Float(value.font.lineHeight)
lineCount = floor(rHeight / charSize)
print("lineCount \(lineCount)")
答案 1 :(得分:0)
我知道这可能对您来说太迟了,但是我认为问题是您的lineHeightMultiple
。