在更改UITextView的字符间距时如何避免这种情况?

时间:2018-09-03 11:13:17

标签: ios swift xcode

我正在尝试更改uitextview的字符间距。但是,它会改变整个外观。 截图:

添加代码之前

Before adding the code

添加代码后

After adding the code

代码(作为扩展名):

extension UITextView {

    func addCharacterSpacing(kernValue: Double = 1.15) {
        if let textValue = text, textValue.count > 0 {
            let attributedString = NSMutableAttributedString(string: textValue)
            attributedString.addAttribute(NSAttributedStringKey.kern, value: kernValue, range: NSRange(location: 0, length: attributedString.length - 1))
            attributedText = attributedString
        }
    }

}

1 个答案:

答案 0 :(得分:0)

如果您使用的是NSMutableAttributedString,则应以与paragraph stylefontsany other settings相同的方式完全自定义它。

从屏幕截图中我看到段落样式存在问题,请手动将其设置为textView

let paragraph = NSMutableParagraphStyle()
paragraph.alignment = .center

textView.attributedText = NSAttributedString(
     string: "string",
     attributes: [.paragraphStyle: paragraph])