我目前正在开发一个 Notes 应用程序,其中有一个 UITextField。当您选择文本时,会出现一个弹出窗口,您可以在其中设置文本格式(请参阅屏幕截图)。我想通过按钮获得该功能。
所以我有一个 UITextfield,用户在其中输入内容,然后我有例如一个显示粗体的按钮,如果用户单击它,只要启用该按钮,即将出现的文本就应该是粗体。
我的问题是“旧”文本总是加粗。这是我目前的解决方案:
var isBoldEnabled = false
override func viewDidLoad() {
super.viewDidLoad()
// Set the initial font for the text field
textField.font = UIFont.systemFont(ofSize: 16)
}
@IBAction func boldButtonTapped(_ sender: Any) {
// Toggle the isBoldEnabled variable
isBoldEnabled = !isBoldEnabled
// Create a new attributed string with the existing text and the current font
let attributedString = NSMutableAttributedString(string: textField.text ?? "")
let attributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: textField.font as Any]
attributedString.addAttributes(attributes, range: NSRange(location: 0, length: attributedString.length))
// If the bold button is enabled, add the bold font attribute for the selected text
if isBoldEnabled {
let boldAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: textField.font!.pointSize) as Any]
let selectedRange = textField.selectedTextRange
if selectedRange != nil {
let range = textField.selectedRange
attributedString.addAttributes(boldAttributes, range: NSRange(location: range.location, length: range.length))
}
}
// Set the attributed text to the text field
textField.attributedText = attributedString
}
有没有人有更好的方法如何仅通过更改即将到来的输入来启用此功能?
谢谢大家
当您尝试“取消加粗”您的文本时,您将默认字体设置为属性字符串作为文本字段中的字体
UIFont.boldSystemFont(ofSize: textField.font!.pointSize) as Any
之前设置为bold
所以,将您的代码更改为
var isBoldEnabled = false
let defaultFont = UIFont.systemFont(ofSize: 16)
override func viewDidLoad() {
super.viewDidLoad()
// Set the initial font for the text field
textField.font = defaultFont
}
@IBAction func boldButtonTapped(_ sender: Any) {
// Toggle the isBoldEnabled variable
isBoldEnabled = !isBoldEnabled
// Create a new attributed string with the existing text and the current font
let attributedString = NSMutableAttributedString(string: textField.text ?? "")
let attributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: defaultFont as Any]
attributedString.addAttributes(attributes, range: NSRange(location: 0, length: attributedString.length))
...
}