0

I need to make the textView bold when the user starts writing, and when the user clicks on the line break ("\n") I need to remove the bold font and put the normal.

How to remove the bold font just after clicking on the line break?

an example of what I need to do is in the iPhone system notes, when you create a new note, the title is written first, after the line break, the font changes. Unfortunately, I can’t attach an image.

I tried to write a condition: if text equals a line break, then change the font to regular, but the font of all text changes.

this my code:

import UIKit
class CreateDiaryViewController: UIViewController {

lazy private var scrollView = UIScrollView()
private let contentView = UIView()
var textViewBottomAnchor = NSLayoutConstraint()

lazy var textView: UITextView = {
    let textView = UITextView()
    textView.backgroundColor = .systemGray6
    textView.font = .systemFont(ofSize: 17, weight: .bold)
    
    return textView
}()

override func viewDidLoad() {
    super.viewDidLoad()
    
    textView.delegate = self
    
    componentsConfigure()
    registerForKeyboardNotificaions()
}

override func viewWillAppear(_ animated: Bool) {
    navigationController?.navigationBar.prefersLargeTitles = false
    navigationItem.backButtonTitle = " "
}

deinit {
    removeKeyboardNotifications()
}

private func componentsConfigure() {
    view.addSubview(textView)
    
    [textView].forEach { $0.translatesAutoresizingMaskIntoConstraints = false }
    textViewBottomAnchor = textView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
    textViewBottomAnchor.isActive = true
    
    NSLayoutConstraint.activate([
        textView.topAnchor.constraint(equalTo: view.topAnchor),
        textView.leftAnchor.constraint(equalTo: view.leftAnchor),
        textView.rightAnchor.constraint(equalTo: view.rightAnchor)
    ])
}
}

here is the method where i tried to change font after line break:

extension CreateDiaryViewController: UITextViewDelegate {
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    if (text == "\n") {
        textView.font = .systemFont(ofSize: 16, weight: .regular)
    }
    return true
}
}
Rakhim
  • 1
  • 2

1 Answers1

0

Try to use textView.attributedText instead of default textView.text if you want to be more than one font in same textView.

Check this link for how to use: How do I make an attributed string using Swift?

Skatox
  • 4,237
  • 12
  • 42
  • 47
Thang Phi
  • 1,641
  • 2
  • 7
  • 16