CNLiveShopTextView.swift
2.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
//
// CNLiveShopTextView.swift
// metaCode
//
// Created by zx on 2023/11/15.
//
import Foundation
class CNLiveShopTextView: UITextView {
/// setNeedsDisplay调用drawRect
var placeHolder: String = ""{
didSet{
self.setNeedsDisplay()
}
}
var placeHolderColor: UIColor = UIColor.gray{
didSet{
self.setNeedsDisplay()
}
}
override var font: UIFont?{
didSet{
self.setNeedsDisplay()
}
}
override var text: String!{
didSet{
self.setNeedsDisplay()
}
}
override var attributedText: NSAttributedString!{
didSet{
self.setNeedsDisplay()
}
}
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
/// default字号
self.font = UIFont.systemFont(ofSize: 14)
NotificationCenter.default.addObserver(self, selector: #selector(textDidChanged(noti:)), name: UITextView.textDidChangeNotification, object: self)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func textDidChanged(noti: NSNotification) {
self.setNeedsDisplay()
}
override func draw(_ rect: CGRect) {
if self.hasText {
return
}
var newRect = CGRect()
newRect.origin.x = 5
newRect.origin.y = 7
let size = self.placeHolder.getStringSize(rectSize: rect.size, font: self.font ?? UIFont.systemFont(ofSize: 14))
newRect.size.width = size.width
newRect.size.height = size.height
/// 将placeHolder画在textView上
(self.placeHolder as NSString).draw(in: newRect, withAttributes: [NSAttributedString.Key.font: self.font ?? UIFont.systemFont(ofSize: 14),NSAttributedString.Key.foregroundColor: self.placeHolderColor])
}
override func layoutSubviews() {
super.layoutSubviews()
self.setNeedsDisplay()
}
deinit {
NotificationCenter.default.removeObserver(self, name: UITextView.textDidChangeNotification, object: self)
}
}
extension String {
/// 计算字符串的尺寸
///
/// - Parameters:
/// - text: 字符串
/// - rectSize: 容器的尺寸
/// - fontSize: 字体
/// - Returns: 尺寸
///
public func getStringSize(rectSize: CGSize,font: UIFont) -> CGSize {
let str: NSString = self as NSString
let rect = str.boundingRect(with: rectSize, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)
return CGSize(width: ceil(rect.width), height: ceil(rect.height))
}
}