iOS UITextField的代理 的幾點筆記


 今天做項目的時候,有個需求,點擊按鈕,就在特定的編輯框輸入按鈕中的文字,一開始我還以C++的思想來寫,先獲取光標的位置,然后在判斷是否在那個編輯框,進行輸入。后來我旁邊的同事看到了直接教我用代理方法,因為接觸iOS沒多久,也不清楚<UITextFieldDelegate>的用法。非常感謝我同事。

1、代理<UITextFieldDelegate>

@interface idiom_ViewController ()<UITextFieldDelegate>
{
    UITextField * _selectTf;
    NSArray *UIButton_array;
}
@property (weak, nonatomic) IBOutlet UITextField *first_idiom;
@property (weak, nonatomic) IBOutlet UITextField *second_idiom;
@property (weak, nonatomic) IBOutlet UITextField *third_idiom;
- (void)viewDidLoad {
    [super viewDidLoad];
    //實現UITextFieldDelegate的協議
    _first_idiom.delegate=self;
    _second_idiom.delegate =self;
    _third_idiom.delegate =self;
    //點擊編輯框隱藏軟鍵盤
    _first_idiom.inputView =[UIView new];
    _second_idiom.inputView =[UIView new];
    _third_idiom.inputView =[UIView new];
    //創建手勢識別對象並監聽手勢
    UITapGestureRecognizer * tap =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction)];
    [self.view addGestureRecognizer:tap];
    // Do any additional setup after loading the view from its nib.
}
//失去焦點
-(void)tapAction{
    [self.view endEditing:YES];
}

-(void)textFieldDidEndEditing:(UITextField *)textField{
    _isBeginTf =NO;
}

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    _isBeginTf =YES;
    _selectTf =textField;
}

2、按鈕點擊事件-編輯框輸入按鈕文字

- (void)button_word:(UIButton *)btn
{
    if (!_isBeginTf) {
        return;
    }
    _selectTf.text = [NSString stringWithFormat:@"%@%@",_selectTf.text,btn.titleLabel.text];
    btn.userInteractionEnabled =NO;
    btn.backgroundColor =[UIColor lightGrayColor];
}

3、刪除按鈕事件

- (IBAction)goBackButtonAction:(id)sender {
    if (!_isBeginTf) {
        return;
    }
    
    if ([_selectTf.text isEqualToString:@""]) {
        return;
    }
    //獲取編輯框最后一個文字
    NSString *gaBackStr =[_selectTf.text substringWithRange:NSMakeRange(_selectTf.text.length-1, 1)];
    //獲取編輯框length -1的文字
    _selectTf.text =[_selectTf.text substringToIndex:_selectTf.text.length -1];
    
    for (int i=0; i<12; i++) {
         UIButton *btn= UIButton_array[i];
        //判斷刪除的文字和按鈕中的文字是否相同
        if ([btn.titleLabel.text isEqualToString:gaBackStr]) {
            //相同,按鈕從不可點擊變為可點擊,顏色改變
            btn.userInteractionEnabled =YES;
            btn.backgroundColor =[UIColor orangeColor];
            return;
        }
    }
    
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM