前言
筆者在最近的項目中需要這樣的效果:用戶輸入驗證碼格式正確的時候,button按鈕才能點擊扔字,并且button的背景色由默認的灰色變?yōu)樗{色泼菌,由于筆者的上個項目用到了通知中心檢測文本框的狀態(tài)谍肤,所以就想到了檢測文本框正在編輯時判斷里面的text屬性來達到這個效果。
具體實現(xiàn)過程
全局登錄button
@property(nonatomic, strong)UIButton * loginButton;//登錄按鈕
self.loginButton = [XSTTools generateButtonWith:UIButtonTypeCustom frame:CGRectZero title:@"下一步" backgroudImgSel:SET_IMAGE(@"#59c3f5") backgroundImgNor:SET_IMAGE(@"#cccccc") backgroundImgHig:SET_IMAGE(@"44b5ea") fontSize:17.0f target:self select:@selector(goExitClicked:) titleSelColor:nil titleNorColor:SET_COLOR(@"ffffff")];//上面是我自己封裝的創(chuàng)建button的類方法
[self.loginButton repairFillet];//這個方法是個類別不用管
self.loginButton.userInteractionEnabled = NO;//先將交互設為NO
[self.view addSubview:self.loginButton];//添加到當前視圖控制器view上
//這里設置好屬性哗伯,selected的顏色和normal顏色
1.1需要在- (void)viewWillAppear:(BOOL)animated方法添加通知中心
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
//添加通知中心
//添加文本框通知中心
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(gosave:) name:UITextFieldTextDidChangeNotification object:nil];
//selector是選擇器荒揣,Observer是觀察者,name是檢測的類型 object填nil就行
//這里檢測的是文本框text值改變的時候焊刹,另外還可以檢測:
UITextFieldTextDidBeginEditingNotification;開始編輯時
UITextFieldTextDidEndEditingNotification;結束編輯時
UITextFieldTextDidChangeNotification;值改變時
}
1.2在當前視圖控制器的.m中實現(xiàn)gosave方法
- (void)gosave:(NSNotification *) Notification{
UITextField * textField = Notification.object;
if (self.phoneTextFld.text.length == 11 && self.codeTextFld.text.length == 4 && [XSTTools judgeWithPhone:self.phoneTextFld.text andWithPwd:nil andWithCode:self.codeTextFld.text andShowView:self.view]) {
//這個if判斷是我自己項目需求寫的系任,你可以根據(jù)自己項目來寫,只需要在滿足條件的時候將button的selected設置為YES不滿足條件設置為NO即可
self.loginButton.selected = YES;
self.loginButton.userInteractionEnabled = YES;
}else{
self.loginButton.selected = NO;
self.loginButton.userInteractionEnabled = NO;
}
//這里可以改變loginButton的selected屬性來達到效果虐块,創(chuàng)建loginButton的時候把屬性設置好俩滥,每次你在textField文本中輸入字符并且text發(fā)生改變時都會調(diào)用gosave方法來檢測
}
1.3移除通知中心
- (void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
//移除通知中心
[[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
[self.timer invalidate];
}
擴展
1.當然上面只是一個很小的用法,你可以擴展其他用法贺奠,比如還可以檢測鍵盤的高度來實現(xiàn)對uikit控件的frame上移和下拉霜旧。這個用法主要用在當textField文本框被彈出鍵盤遮擋時。
ps:需要注意的是:
1.1添加通知中心一定要寫在視圖即將顯示的方法-(void)viweWillApper:(animated)里面儡率,不能寫在-(void)viewDidLoad里面挂据。
1.2視圖即將消失的時候將通知中心移除,不然會有內(nèi)存泄露儿普。
因為:viewDidLoad只會在UIViewController的實例化對象push或者present的時候執(zhí)行一次崎逃。所以當我們返回這個視圖的時候通知中心已經(jīng)移除了,就會出錯眉孩。