UITextView 多行輸入框
加入協定
class ViewController: UIViewController, UITextViewDelegate {
宣告資料
var textview = UITextView()
var placeholder = UILabel()
var donebtn = UIButton()
let WIDTH = UIScreen.main.bounds.size.width
viewDidLoad
view.backgroundColor = .lightGray
textview.frame.size = CGSize(width: 200,
height: 100)
textview.center = CGPoint(x: WIDTH / 2,
y: 100)
textview.backgroundColor = .white
textview.delegate = self
textview.textColor = .black
textview.font = UIFont(name: "Helvetica-Light",
size: 13)
textview.allowsEditingTextAttributes = true
textview.showsVerticalScrollIndicator = false
textview.showsHorizontalScrollIndicator = false
textview.dataDetectorTypes = .all
textview.autocapitalizationType = .none
textview.textAlignment = .natural
textview.layer.cornerRadius = 10
textview.layer.borderWidth = 2
textview.layer.borderColor = UIColor.black.cgColor
view.addSubview(textview)
placeholder.frame.size = CGSize(width: 190,
height: 20)
placeholder.center = CGPoint(x: WIDTH / 2,
y: 80)
placeholder.text = " 點選輸入"
placeholder.textColor = .lightGray
placeholder.backgroundColor = .white
placeholder.font = UIFont.systemFont(ofSize: 13)
placeholder.layer.cornerRadius = 10
view.addSubview(placeholder)
donebtn.frame.size = CGSize(width: 80,
height: 40)
donebtn.center = CGPoint(x: WIDTH / 2,
y: 190)
donebtn.backgroundColor = .red
donebtn.setTitle("結束編輯",
for: .normal)
donebtn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 13)
donebtn.setTitleColor(.white,
for: .normal)
donebtn.addTarget(self,
action: #selector(donebtnpressed),
for: .touchUpInside)
donebtn.isHidden = true
view.addSubview(donebtn)
建立編輯觸發動作
func textViewDidBeginEditing(_ textView: UITextView) {
self.placeholder.center = CGPoint(x: WIDTH / 2,
y: 65)
self.placeholder.text = " 輸入中..."
self.placeholder.textColor = .blue
self.donebtn.isHidden = false
}
建立關閉鍵盤動作
func donebtnpressed(sender:UIButton){
self.view.endEditing(true)
self.donebtn.isHidden = true
self.placeholder.textColor = .lightGray
if self.textview.text.isEmpty {
self.placeholder.center = CGPoint(x: WIDTH / 2,
y: 80)
self.placeholder.text = " 點選輸入"
}
else {
self.placeholder.text = " 點選修改"
}
}
更多常用設定
func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
}
func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
}
func textViewDidEndEditing(_ textView: UITextView) {
}
func textViewDidChange(_ textView: UITextView) {
}
func textViewDidChangeSelection(_ textView: UITextView) {
}