ストーリーボードに UITextView があります (テキスト プロパティに属性があり、編集可能な属性が選択され、編集可能がチェックされています)。ユーザーがボタンを押すと、太字フォントを「アクティブ化」したい。したがって、そこからユーザーが入力するものはすべて太字にする必要があります。Return キーが押されたら、次の行に移動したいので、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
}
私が達成しようとしている別の例は、stackoverflow 編集効果です。「{}」アイコンを押すと、「コーディング可能モード」になります。キーボードでEnterキーを押すと、通常に戻ります。
regularText および boldText プロパティは、サイズ 14 のシステム フォントです。