class FirstLineFormatVC: UIViewController, UITextViewDelegate {
let tv = UITextView()
let firstLineAttributes: [NSAttributedString.Key : Any] = [
.font: UIFont.systemFont(ofSize: 20.0, weight: .bold),
]
let normalAttributes: [NSAttributedString.Key : Any] = [
.font: UIFont.systemFont(ofSize: 16.0, weight: .regular),
]
override func viewDidLoad() {
super.viewDidLoad()
tv.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(tv)
let g = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
tv.topAnchor.constraint(equalTo: g.topAnchor, constant: 20.0),
tv.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0),
tv.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0),
tv.heightAnchor.constraint(equalToConstant: 300.0),
])
tv.delegate = self
// give it a background color so we can see it
tv.backgroundColor = .yellow
}
func textViewDidChange(_ textView: UITextView) {
//formatTextInTextView(textView: textView)
textView.isScrollEnabled = false
let selectedRange = textView.selectedRange
let text = textView.text ?? ""
// set full string to normalAttributes
let attributedString = NSMutableAttributedString(string: text, attributes: normalAttributes)
// get the first line
let range = text.lineRange(for: ..<text.startIndex)
let nsRange = NSRange(range, in: text)
// set first line to firstLineAttributes
attributedString.addAttributes(firstLineAttributes, range: nsRange)
// update the attributedText
textView.attributedText = attributedString
textView.selectedRange = selectedRange
textView.isScrollEnabled = true
}
}
1条答案
按热度按时间fae0ux8s1#
我只对它做了非常快速的测试,它的工作原理并不像苹果笔记,但它可能足以满足你的需要。
希望这至少是个起点。