美文网首页
自定义UITextField

自定义UITextField

作者: Waisti | 来源:发表于2017-04-12 11:47 被阅读74次

    自定义UITextField类

    #import "WZTextField.h"

    @implementation WZTextField

    // 修改文本展示区域,一般跟editingRectForBounds一起重写

    - (CGRect)textRectForBounds:(CGRect)bounds

    {

    CGRect inset = CGRectMake(bounds.origin.x+10, bounds.origin.y, bounds.size.width-25, bounds.size.height);//更好理解些

    return inset;

    }

    // 重写来编辑区域,可以改变光标起始位置,以及光标最右到什么地方,placeHolder的位置也会改变

    -(CGRect)editingRectForBounds:(CGRect)bounds

    {

    CGRect inset = CGRectMake(bounds.origin.x+10, bounds.origin.y, bounds.size.width-25, bounds.size.height);//更好理解些

    return inset;

    }

    //修改rightView的位置

    - (CGRect) rightViewRectForBounds:(CGRect)bounds {

    CGRect textRect = [super rightViewRectForBounds:bounds];

    textRect.origin.x -= 10;

    return textRect;

    }

    @end

    在控制器中的使用:

    - (void)viewDidLoad {

    [super viewDidLoad];

    WZTextField *tfView = [[WZTextField alloc]initWithFrame:CGRectMake(50, 50, 200, 30)];

    //    tfView.backgroundColor = [UIColor grayColor];

    //提示文字

    tfView.placeholder = @"输入商品";

    //圆角

    //    tfView.keyboardAppearance = UIKeyboardAppearanceAlert;

    //改用layer圆角

    tfView.layer.cornerRadius = 12;

    tfView.layer.borderWidth = 1;

    tfView.layer.borderColor = [UIColor colorWithRed:38/255.0 green:187/255.0 blue:155/255.0 alpha:1.0]

    .CGColor;

    tfView.tintColor = [UIColor redColor];

    tfView.layer.masksToBounds = YES;

    //    tfView.text = @"初始化文字";

    //右边的x号,点击清除输出 如果设置了rightView 会被覆盖

    tfView.clearButtonMode = UITextFieldViewModeWhileEditing;

    //.rightView

    UIImageView *leftView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];

    leftView.image = [UIImage imageNamed:@"search"];

    tfView.rightView =leftView;

    tfView.rightViewMode = UITextFieldViewModeAlways;

    [self.view addSubview:tfView];

    }

    相关文章

      网友评论

          本文标题:自定义UITextField

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