Reputation: 79
I want to increase the Line Spacing in UILabel but I can't figure it out how.
I found this solution [https://stackoverflow.com/a/39158698/8633963] on Stackoverflow but my Xcode always displays this:
Use of unresolved identifier 'NSParagraphStyleAttributeName'
I think the answer is right but it did not work for me. Can anyone help with this problem?
Upvotes: 2
Views: 9892
Reputation: 101
Swift 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
}
}
Upvotes: 9
Reputation: 651
This worked for me.
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
}
}
}
Upvotes: 1
Reputation: 163
Check out this ridiculously simple solution that works!
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
}
//Notice the use of the \n to load a return or as many as you wish. Make sure they are within a string designation.
Upvotes: -2
Reputation: 4538
In Swift 4 in this case you have to use NSAttributedStringKey.paragraphStyle
instead of NSParagraphStyleAttributeName
Upvotes: 3