swift 编辑UIKit中的UITextField,以便可以通过按钮编辑文本

brccelvz  于 2023-02-28  发布在  Swift
关注(0)|答案(2)|浏览(143)

我目前正在开发一个笔记应用程序,我有一个UITextField。当你选择文本有一个弹出窗口,你可以格式化文本(见截图)。我想有通过按钮的功能。
因此,我有一个UIText字段,用户在其中键入内容,然后我有一个按钮,显示为粗体,如果用户单击它,则接下来的文本应该是粗体,只要启用了该按钮。
我的问题是“旧”文本总是加粗。这是我目前的解决方案:

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
}

有没有人有更好的方法,如何才能启用这个功能,只需改变即将到来的打字?感谢所有

ukdjmx9f

ukdjmx9f1#

取决于你想做多少...
对于复杂的、功能齐全的"富文本编辑",我建议搜索已经构建的解决方案--有很多开源的解决方案。如果你不能找到一个完全满足你需要的解决方案,我相信你可以找到一个足够接近的解决方案,你可以浏览代码并编辑它以满足你的需要。
对于一个相当简单的实现,您可以设置文本字段的.typingAttributes-参见Apple的docs
这里有一个非常简单的例子:

class ViewController: UIViewController {
    
    let textField = UITextField()
    
    let normalFont: UIFont = .systemFont(ofSize: 17, weight: .regular)
    let boldFont: UIFont = .systemFont(ofSize: 17, weight: .bold)
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor(white: 0.95, alpha: 1.0)
        
        textField.borderStyle = .roundedRect
        textField.font = normalFont
        
        let v = UILabel()
        v.text = "Bold on/off"
        
        let sw = UISwitch()
        
        let ctrlStack = UIStackView(arrangedSubviews: [v, sw])
        ctrlStack.spacing = 8
        
        ctrlStack.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(ctrlStack)
        
        textField.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(textField)
        
        let g = view.safeAreaLayoutGuide
        
        NSLayoutConstraint.activate([
            
            ctrlStack.topAnchor.constraint(equalTo: g.topAnchor, constant: 20.0),
            ctrlStack.centerXAnchor.constraint(equalTo: g.centerXAnchor),
            
            textField.topAnchor.constraint(equalTo: ctrlStack.bottomAnchor, constant: 20.0),
            textField.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 40.0),
            textField.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -40.0),

        ])
        
        sw.addTarget(self, action: #selector(swChanged(_:)), for: .valueChanged)
    }
    
    @objc func swChanged(_ sender: UISwitch) {
        textField.typingAttributes?[NSAttributedString.Key.font] = sender.isOn ? boldFont : normalFont
    }
}

看起来像这样:

轻触开关以启用粗体"On",然后再键入一些内容:

关闭粗体并输入更多内容:

pftdvrlh

pftdvrlh2#

当你试图“取消粗体”你的文本,你设置默认字体属性字符串作为字体从你的文本字段

UIFont.boldSystemFont(ofSize: textField.font!.pointSize) as Any

以前设置为粗体
因此,将代码更改为

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))
    ...
}

相关问题