UITextView не запоминает стили шрифта при нажатии клавиши возврата на клавиатуре

У меня есть UITextView в раскадровке (свойство текста приписывается, и проверяются атрибуты Разрешить редактирование, выбранные, редактируемые). Когда пользователь нажимает кнопку, я хочу "активировать" жирный шрифт. Таким образом, все, что пользователь вводит оттуда, должно быть выделено жирным шрифтом. И когда клавиша возврата нажата, я хочу перейти к следующей строке, и UITextView должен помнить атрибуты всего текста. Проблема в том, что после того, как я нажимаю клавишу возврата, все символы становятся жирным шрифтом.

Вот что я имею в коде.

var isBoldTyping: Bool = false

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    print("text: \(text)", range)
    if text == "\n" {
        textView.text.append("\n")


        if isBoldTyping {
            //textView.typingAttributes = [NSAttributedStringKey.font.rawValue: regularText]
            isBoldTyping = false
        }

    }

    if isBoldTyping {
        textView.textStorage.beginEditing()
        textView.textStorage.addAttributes([NSAttributedStringKey.font: boldText], range: range)
        print("Atttributed adding")
        textView.textStorage.endEditing()
    } else {
        textView.textStorage.beginEditing()
        textView.textStorage.addAttributes([NSAttributedStringKey.font: regularText], range: range)
        print("Atttributed adding")
        textView.textStorage.endEditing()
    }

    return true
}

Другой пример того, чего я пытаюсь достичь, - это эффект редактирования стека переполнения. Когда я нажимаю значок "{}", я нахожусь в "кодируемом режиме". При нажатии Enter на клавиатуре он возвращается в нормальное состояние.

Свойства normalText и boldText - это просто системный шрифт размером 14.

1 ответ

Только то что тебе нужно typingAttributes, если я четко понял, чего вы пытаетесь достичь. Вы должны отключить жирный шрифт, когда \n появляется в replacementText через typingAttributes, Я пишу небольшой пример для вас

class ViewController: UIViewController, UITextViewDelegate {

    let textView = UITextView()
    let boldButton = UIButton(type: .system)

    override func viewDidLoad() {
        super.viewDidLoad()

        textView.translatesAutoresizingMaskIntoConstraints = false
        textView.delegate = self
        textView.typingAttributes = [NSAttributedStringKey.font.rawValue: UIFont.systemFont(ofSize: 14.0)]

        view.addSubview(textView)

        view.addConstraint(NSLayoutConstraint(item: view, attribute: .leading, relatedBy: .equal, toItem: textView, attribute: .leading, multiplier: 1.0, constant: 0.0))
        view.addConstraint(NSLayoutConstraint(item: view, attribute: .top, relatedBy: .equal, toItem: textView, attribute: .top, multiplier: 1.0, constant: 0.0))
        view.addConstraint(NSLayoutConstraint(item: view, attribute: .bottom, relatedBy: .equal, toItem: textView, attribute: .bottom, multiplier: 1.0, constant: 0.0))
        view.addConstraint(NSLayoutConstraint(item: view, attribute: .trailing, relatedBy: .equal, toItem: textView, attribute: .trailing, multiplier: 1.0, constant: 0.0))

        boldButton.setTitle("BOLD", for: .normal)
        boldButton.addTarget(self, action: #selector(toggleBold), for: .touchUpInside)
        boldButton.translatesAutoresizingMaskIntoConstraints = false

        view.addSubview(boldButton)
        view.addConstraint(NSLayoutConstraint(item: view, attribute: .leading, relatedBy: .equal, toItem: boldButton, attribute: .leading, multiplier: 1.0, constant: 0.0))
        view.addConstraint(NSLayoutConstraint(item: boldButton, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 64.0))
        view.addConstraint(NSLayoutConstraint(item: view, attribute: .bottom, relatedBy: .equal, toItem: boldButton, attribute: .bottom, multiplier: 1.0, constant: 0.0))
        view.addConstraint(NSLayoutConstraint(item: view, attribute: .trailing, relatedBy: .equal, toItem: boldButton, attribute: .trailing, multiplier: 1.0, constant: 0.0))

    }

    @objc func toggleBold() {
        boldButton.isSelected = !boldButton.isSelected
        if boldButton.isSelected {
            textView.typingAttributes = [NSAttributedStringKey.font.rawValue: UIFont.boldSystemFont(ofSize: 14.0)]
        } else {
            textView.typingAttributes = [NSAttributedStringKey.font.rawValue: UIFont.systemFont(ofSize: 14.0)]
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if text.contains("\n") && boldButton.isSelected {
            toggleBold()
        }
        return true
    }

}
Другие вопросы по тегам