我想增加 UILabel 中的行间距,但我不知道怎么做。
我在 Stackoverflow 上找到了这个解决方案 [ https://stackoverflow.com/a/39158698/8633963],但我的 Xcode 总是显示这个:
Use of unresolved identifier 'NSParagraphStyleAttributeName'
我认为答案是正确的,但它对我不起作用。任何人都可以帮助解决这个问题吗?
我想增加 UILabel 中的行间距,但我不知道怎么做。
我在 Stackoverflow 上找到了这个解决方案 [ https://stackoverflow.com/a/39158698/8633963],但我的 Xcode 总是显示这个:
Use of unresolved identifier 'NSParagraphStyleAttributeName'
我认为答案是正确的,但它对我不起作用。任何人都可以帮助解决这个问题吗?
斯威夫特 5
import UIKit
extension UILabel {
func setLineHeight(lineHeight: CGFloat) {
guard let text = self.text else { return }
let attributeString = NSMutableAttributedString(string: text)
let style = NSMutableParagraphStyle()
style.lineSpacing = lineHeight
attributeString.addAttribute(
NSAttributedString.Key.paragraphStyle,
value: style,
range: NSMakeRange(0, attributeString.length))
self.attributedText = attributeString
}
}
在这种情况下,在 Swift 4 中,您必须使用NSAttributedStringKey.paragraphStyle
而不是NSParagraphStyleAttributeName
这对我有用。
import UIKit
extension UILabel {
func setLineHeight(lineHeight: CGFloat) {
let text = self.text
if let text = text {
let attributeString = NSMutableAttributedString(string: text)
let style = NSMutableParagraphStyle()
style.lineSpacing = lineHeight
attributeString.addAttribute(NSParagraphStyleAttributeName, value: style, range: NSMakeRange(0, count(text)))
self.attributedText = attributeString
}
}
}
看看这个可行的非常简单的解决方案!
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CommentTVCCell
// Configure the cell...
cell.myLabel?.text = "\n[\(indexPath.row + 1)]\n\n" + itemArray[indexPath.row].name
//
return cell
}
//注意使用 \n 来加载返回值或任意数量。确保它们在字符串指定范围内。