ios - 用户开始输入时如何记住 UITextView 中的文本属性

标签 ios swift uitextview uitextviewdelegate

我正在使用 UITextView 并尝试在用户键入时使用 attributedText 属性显示文本。

这是我当前的代码:

textView.attributedText = NSMutableAttributedString(
    string: "",
    attributes: [
        NSFontAttributeName: UIFont(name: "AvenirNextLTPro-Regular", size: 12.5)!,
        NSForegroundColorAttributeName: UIColor.colorFromCode(0x262626),
        NSKernAttributeName: 0.5,
        NSParagraphStyleAttributeName: paragraphStyle
    ]
)

问题是,如果您提供一个空字符串,当用户开始输入时,文本不会使用 attributedText 属性进行格式化。

但是,我注意到如果我提供一个字符串,当用户开始附加该字符串时,文本会使用 attributedText 属性进行格式化。

我能想到的完成我需要的唯一方法是重写这个函数,并在每次用户输入键时将文本设置为 attributedText:

func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool

没有其他更好的方法吗?

最佳答案

您需要使用 typingAttributes 属性,而不是设置一个空的属性字符串。

textView.typingAttributes = [
    NSFontAttributeName: UIFont(name: "AvenirNextLTPro-Regular", size: 12.5)!,
    NSForegroundColorAttributeName: UIColor.colorFromCode(0x262626),
    NSKernAttributeName: 0.5,
    NSParagraphStyleAttributeName: paragraphStyle
]

另见 official documentation .

The attributes to apply to new text being entered by the user.

关于ios - 用户开始输入时如何记住 UITextView 中的文本属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31947665/

相关文章:

ios - 使用 UIAppearence 设置 UITableViewCell 选择的背景颜色不起作用

ios - 当更改源为共享扩展时,@FetchRequest 结果未在 SwiftUI 中更新

ios - UITextView 不更改 textColor 属性

ios - React Native IOS 状态栏背景

ios - 将 Vision boundingBox 从 VNFaceObservation 转换为矩形以在图像上绘制

ios - UICollectionView moveItemAtIndexPath :toIndexPath: issues moving items not on screen

iphone - 不使用 reloadData 实时调整 UITableViewCell 大小?

ios - 不相关的 iOS 团队代理许可协议(protocol)消息

ios - navigationController 在 Swift XCTest 案例中为 nil

ios - 如何在 iOS 上突出显示多个文本片段?