不多說直接附上code跟模擬畫面
import UIKit
class ViewController: UIViewController,UITextFieldDelegate,UITextViewDelegate {
var singleFingerTap:UITapGestureRecognizer!
var text1Bool:Bool!
@IBOutlet weak var textfield1: UITextField!
@IBOutlet weak var textfield2: UITextField!
@IBOutlet weak var btn1: UIButton!
@IBOutlet weak var btn2: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//監聽鍵盤動作
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown), name: NSNotification.Name.UIKeyboardWillShow, object: nil);
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasHidden), name: NSNotification.Name.UIKeyboardWillHide, object: nil);
singleFingerTap = UITapGestureRecognizer.init(target: self, action: #selector(handleSingleTap));
self.textfield1.delegate = self
self.textfield2.delegate = self
textfield1.clearButtonMode = .always
textfield2.clearButtonMode = .always
btn1.backgroundColor = UIColor.red
btn2.backgroundColor = UIColor.gray
btn1.tintColor = UIColor.white
btn2.tintColor = UIColor.white
text1Bool = false
textfield1.addTarget(self, action: #selector(text1(textfield:)), for: .allEditingEvents)
textfield2.addTarget(self, action: #selector(text2(textfield:)), for: .allEditingEvents)
}
func btn1c(){
if (text1Bool == true){
btn1.backgroundColor = UIColor.brown
}else{
btn1.backgroundColor = UIColor.red
}
}
func text1(textfield:UITextField){
// if ((textfield.text?.characters.count)! < 2){
if (textfield1.text != ""){
text1Bool = true
}else{
text1Bool = false
}
self.btn1c()
}
func text2(textfield:UITextField){
self.btn2.isEnabled = (textfield.text?.characters.count)! > 2
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: 鍵盤監聽動作(當用戶點view收起)
func keyboardWasShown(){
self.view.addGestureRecognizer(singleFingerTap);
}
func keyboardWasHidden(){
self.view.removeGestureRecognizer(singleFingerTap);
}
func handleSingleTap(){
//Do stuff here...
textfield1.resignFirstResponder()
textfield2.resignFirstResponder()
}
@IBAction func Btn1(_ sender: Any) {
print(textfield1.text!)
}
@IBAction func Btn2(_ sender: Any) {
print(textfield2.text!)
}
}
希望能夠幫助到有需要的朋友們唷^^
雖然手法有點粗操,有更好的方法歡迎提供!