宽窄优行-由【嘉易行】项目成品而来
younger_times
2023-07-05 0d8f5fc8a516bfd07e425909e4a4432600572ee7
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
89
90
91
92
93
94
95
96
97
//
//  YYTextView.swift
//  OKProject
//
//  Created by alvin_y on 2020/5/28.
//  Copyright © 2020 yangwang. All rights reserved.
//
 
import Foundation
 
@IBDesignable class YYTextView: UITextView {
    
    /// 占位字符串
    @IBInspectable var placeholder: String = ""
    
    /// 最大可输入字数
    @IBInspectable var maximumLength: Int = 0
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
        initialization()
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        
        initialization()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        setNeedsDisplay()
    }
    
    private func initialization() {
        NotificationCenter.default.addObserver(self, selector: #selector(textViewTextDidChange(sender:)), name: UITextView.textDidChangeNotification, object: nil)
        
    }
    
    @objc private func textViewTextDidChange(sender: Notification) {
        
        let string = text
        let inputMode = textInputMode?.primaryLanguage; // 键盘输入模式
        
        if (maximumLength > 0) {
            
            if (inputMode == "zh-Hans") {
                
                let selectedRange: UITextRange? = markedTextRange
                
                if selectedRange == nil {
                    
                    let substring = string!.prefix(maximumLength)
                    
                    text = String(substring)
                }
                
            } else {
                
                if string!.count > maximumLength {
                    
                    let substring = string!.prefix(maximumLength)
                    text = String(substring)
                }
            }
        }
        
        setNeedsDisplay()
    }
    
    override func draw(_ rect: CGRect) {
        
        guard !hasText else { return }
        
        // 属性
        let attributes: [NSAttributedString.Key : Any] = [.font: font!, .foregroundColor: UIColor.lightGray]
        
        // 画文字
        var aRect = CGRect.zero
        aRect.origin.x = 5
        aRect.origin.y = 8
        aRect.size.width = rect.size.width - (2 * aRect.origin.x)
        aRect.size.height = rect.size.height
        
        let string = placeholder as NSString
        
        string.draw(in: aRect, withAttributes: attributes)
 
    }
}