无法使用UITextView应用行间距?

时间:2017-03-23 02:51:46

标签: ios swift uitextview

您对UITextView的行间距有什么想法吗?我无法应用它。下面是我的代码。

import UIKit

class DetailViewController: UIViewController {
    @IBOutlet weak var itemTextView: UITextView!
    var txtString: String?
    var txtTitleBar:String?

    override func viewDidLoad() {
        super.viewDidLoad()
        //navigationController?.navigationItem.title = "Love"
        self.title = txtTitleBar

        //self.tabBarController?.navigationItem.title = "My Title"
        itemTextView.text = txtString
        itemTextView.font = UIFont(name: "Arial-Regular", size:20)
        itemTextView.font = .systemFont(ofSize: 25)
        (itemTextView.font?.lineHeight)! * 5
    }
}

enter image description here

4 个答案:

答案 0 :(得分:12)

您需要使用属性字符串并指定段落样式。例如:

let style = NSMutableParagraphStyle()
style.lineSpacing = 20
let attributes = [NSParagraphStyleAttributeName : style]
textView.attributedText = NSAttributedString(string: txtString, attributes: attributes)

有关归因字符串用法的更多详细信息,请参阅此SO答案:How do I make an attributed string using Swift?

答案 1 :(得分:4)

Xcode 9.2 Swift 4

let style = NSMutableParagraphStyle()
style.lineSpacing = 0
let attributes = [NSAttributedStringKey.paragraphStyle : style]
txtViewAbout.attributedText = NSAttributedString(string: txtViewAbout.text, attributes: attributes)

答案 2 :(得分:1)

Xcode 10.1 Swift 4.2

    let style = NSMutableParagraphStyle()
    style.lineSpacing = 19
    let atributes = [NSAttributedString.Key.paragraphStyle: style ]
    textView.attributedText = NSAttributedString(string: model.text, attributes: atributes)

答案 3 :(得分:0)

使用typingAttributes 将确保这些属性适用于用户输入的新文本。

    let style = NSMutableParagraphStyle()
    style.lineSpacing = 10
    let attributes = [NSAttributedString.Key.paragraphStyle : style )
    ]
    textView.typingAttributes = attributes