欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

iOS UITextField的代理的几点笔记

程序员文章站 2023-01-13 20:39:41
今天做项目的时候,有个需求,点击按钮,就在特定的编辑框输入按钮中的文字,一开始我还以C++的思想来写,先获取光标的位置,然后在判断是否在那个编辑框,进行输入。后来我旁边的同事看到了直接教我用代理方法,因为接触iOS没多久,也不清楚的用法。非常感谢我同事。 1 ......

 今天做项目的时候,有个需求,点击按钮,就在特定的编辑框输入按钮中的文字,一开始我还以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;
        }
    }
    
}