UITextView
常用的属性
1
2let textView = UITextView()
3
4// 设置输入文字的样式属性
5textView.typingAttributes = [
6 .font: UIFont.systemFont(ofSize: 16),
7 .foregroundColor: UIColor.black
8]
9
10// 设置链接文字的样式属性
11textView.linkTextAttributes = [
12 .foregroundColor: UIColor.blue,
13 .underlineStyle: NSUnderlineStyle.single
14]
15
16// 设置键盘上的附加视图
17textView.inputAccessoryView = UIToolbar(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 44))
插入、删除、替换内容
1
2public func updateCursorPosition(range: NSRange) {
3 self.selectedRange = range
4}
5
1public func insertAttrStringAtCursor(AttrString string: NSAttributedString) {
2 // self: UITextView 自身
3 // 插入属性文本到光标位置
4 self.textStorage.insert(string, at: self.selectedRange.location)
5 // 计算光标位置
6 let cursorRange = NSRange(location: self.selectedRange.location + string.length, length: 0)
7 // 更新光标位置
8 updateCursorPosition(range: cursorRange)
9 // 调用自身的代理
10 self.delegate?.textViewDidChange?(self)
11}
1public func replace(AttrString string: NSAttributedString, ForRange range: NSRange) {
2 // 替换属性文本到指定位置
3 self.textStorage.replaceCharacters(in: range, with: string)
4 // 计算光标位置
5 let cursorRange = NSRange(location: range.location + string.length, length: 0)
6 // 更新光标位置
7 updateCursorPosition(range: cursorRange)
8 // 调用自身的代理
9 self.delegate?.textViewDidChange?(self)
10}
1
2public func deleteAttrString(ForRange range: NSRange) {
3 // 删除指定位置的属性文本
4 self.textStorage.deleteCharacters(in: range)
5 // 计算光标位置
6 let cursorRange = NSRange(location: range.location, length: 0)
7 // 更新光标位置
8 updateCursorPosition(range: cursorRange)
9 // 调用自身的代理
10 self.delegate?.textViewDidChange?(self)
11}