美文网首页OC-开发案例收集
1.0(oc)UITextField自定义clearButton

1.0(oc)UITextField自定义clearButton

作者: 淡闲星草 | 来源:发表于2017-10-12 16:30 被阅读39次

    最终效果截图

    更改后截图.png

    核心代码

    注意
    按钮frame必须设置 否则 点击删除键后 clearButton 会变小(系统默认是1919)*
    主要是使用了KVC方面的知识

    // 按钮
    
    UIButton *clearButton = [textField valueForKey:@"_clearButton"];
    //frame必须设置 否则 点击删除键后 clearButton 会变小(系统默认是19*19)
    clearButton.frame = CGRectMake(0, 0, 30, 30);
    [clearButton setImage:[UIImage imageNamed:@"Placeholder_clearBtn"] forState:UIControlStateNormal];
    [clearButton setImage:[UIImage imageNamed:@"Placeholder_clearBtn_selected"] forState:UIControlStateHighlighted];
    [clearButton setImage:[UIImage imageNamed:@"Placeholder_clearBtn_selected"] forState:UIControlStateSelected];
    

    QYXAddCardTextFieldView.h 文件

    #import <UIKit/UIKit.h>
    
    @interface QYXAddCardTextFieldView : UIView
    @property (nonatomic, strong)   UITextField * textField;
    @end
    

    QYXAddCardTextFieldView.m文件

    #import "QYXAddCardTextFieldView.h"
    @interface QYXAddCardTextFieldView()<UITextFieldDelegate>
    @end
    @implementation QYXAddCardTextFieldView
    - (instancetype)initWithFrame:(CGRect)frame
    {
    if (self = [super initWithFrame:frame]) {
    
    //1.背景
    UIImageView * textFieldBG = [[UIImageView alloc] initWithImage:[UIImage resizedImageWithName:@"TextFieldBG"]];
    textFieldBG.frame = CGRectMake(0, 0, self.width, self.height);
    [self addSubview:textFieldBG];
    
    //2.textfield
    UITextField * textField = [[UITextField alloc] initWithFrame:CGRectMake(QYXSmallViewMargin, 0, self.width - QYXBigViewMargin, self.height)];
    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    textField.keyboardType = UIKeyboardTypeASCIICapable;
    textField.returnKeyType = UIReturnKeyDone;
    textField.delegate = self;
    
    [textField setValue:QYXNormalFont forKeyPath:@"_placeholderLabel.font"];
     textField.textColor = [UIColor whiteColor];
    // textField.adjustsFontSizeToFitWidth = YES;
    textField.font = iphone5 ? QYXNormalSubFont : QYXNormalFont;
    [self addSubview:textField];
    self.textField = textField;
    
    
    //2.1 -- 删除按钮
    UIButton *clearButton = [textField valueForKey:@"_clearButton"];
    clearButton.frame = CGRectMake(0, 0, 30, 30);
    [clearButton setImage:[UIImage imageNamed:@"Placeholder_clearBtn"] forState:UIControlStateNormal];
    [clearButton setImage:[UIImage imageNamed:@"Placeholder_clearBtn_selected"] forState:UIControlStateHighlighted];
    [clearButton setImage:[UIImage imageNamed:@"Placeholder_clearBtn_selected"] forState:UIControlStateSelected];
    
    
    }
      return self;
    }
    @end
    

    相关文章

      网友评论

        本文标题:1.0(oc)UITextField自定义clearButton

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