美文网首页
2022-06-20 iOS UITextField 清除按钮自

2022-06-20 iOS UITextField 清除按钮自

作者: nickNic | 来源:发表于2022-06-20 16:39 被阅读0次

    因为设计原因,需要更改下iOS原生的清除按钮,经过研究可使用rightView方式添加自定义按钮,代码如下

    #import <UIKit/UIKit.h>
    @interface UITextField (ClearBtn)
    @property (nonatomic,strong) UIButton *clearBtn;
    @property (nonatomic,strong) UIView *clearView;
    - (void)customClearBtnDefaultStyle;
    @end
    
    #import<objc/runtime.h>
    #import "UITextField+ClearBtn.h"
    static const void *clearBtnKey = &clearBtnKey;
    static const void *clearViewKey = &clearViewKey;
    @implementation UITextField (ClearBtn)
    @dynamic clearBtn, clearView;
    - (void)customClearBtnDefaultStyle {
      UIButton *clearBtn = [UIButton buttonWithType:UIButtonTypeCustom];
      clearBtn.size = CGSizeMake(14, 14);//肉眼可见的按钮尺寸大小
     [clearBtn setBackgroundImage: (g_nSkinType == tztSkin_White) ? [UIImage imageTztNamed:@"TZTBaseTextFieldClearBG.png"] : [UIImage imageTztNamed:@"zt_black_clear"] forState:UIControlStateNormal];
     [clearBtn addTarget:self action:@selector(clickClearBtn) forControlEvents:UIControlEventTouchUpInside];
     clearBtn.hidden = YES;
     self.clearBtn = clearBtn;
    
      UIView *clearView = [[UIView alloc]init];
      clearView.size = CGSizeMake(30, 30);//实际按钮尺寸大小,增加用户的点击范围
      [clearView addSubview:clearBtn];
      clearBtn.frameMaxX = clearView.frameMaxX;
     clearBtn.centerY = clearView.centerY;
      clearView.hidden = YES;
      self.clearView = clearView;
      self.rightView = clearView;
      self.rightViewMode = UITextFieldViewModeWhileEditing;
    
      [self addTarget:self action:@selector(textFieldDidEditing:) forControlEvents:UIControlEventEditingChanged];
    
      UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickClearBtn)];
      [clearView addGestureRecognizer:tap];
    }
    
    - (void)setClearBtn:(UIButton *)clearBtn
    {
        objc_setAssociatedObject(self, clearBtnKey,clearBtn, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    -(UIButton *)clearBtn
    {
        return objc_getAssociatedObject(self,clearBtnKey);
    }
    
    - (void)setClearView:(UIView *)clearView
    {
        objc_setAssociatedObject(self, clearViewKey,clearView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    - (UIView *)clearView
    
        return objc_getAssociatedObject(self,clearViewKey);
    }
    //清除的时候隐藏
    - (void)clickClearBtn {
        self.text = @"";
        self.clearBtn.hidden = YES;
        self.clearView.hidden = YES;
    }
    //编辑的时候显示按钮
    - (void)textFieldDidEditing:(UITextField *)textField {
        self.clearBtn.hidden = NO;
        self.clearView.hidden = NO;
    }
    @end
    

    使用的时候直接这样调用即可 [passwordTF customClearBtnDefaultStyle];

    相关文章

      网友评论

          本文标题:2022-06-20 iOS UITextField 清除按钮自

          本文链接:https://www.haomeiwen.com/subject/szejvrtx.html