美文网首页ios学习资料
UITextfield rightview位置太靠边缘的问题

UITextfield rightview位置太靠边缘的问题

作者: 来宝 | 来源:发表于2016-05-09 11:52 被阅读3418次

最近给textfield添加了rightview 代码如下:

    UITextField *searchField = [UITextField textFieldWithFrame:CGRectMake(0, 0, kWidth-100, 30) placeholder:@"  搜索店铺" textColor:[UIColor grayColor]];
    searchField.font = [UIFont systemFontOfSize:14];
    searchField.backgroundColor = [UIColor whiteColor];
    searchField.layer.masksToBounds = YES;
    searchField.layer.cornerRadius = 2;
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
    imageView.image = [UIImage imageNamed:@"搜索"];
    searchField.rightView = imageView;
    searchField.rightViewMode = UITextFieldViewModeAlways;//一定要加上这句代码
    self.navigationItem.titleView = searchField;

0BDCE698-8811-424E-9059-2D8DAD449C8A.png

放大镜的位置太靠近右边缘,怎么才能往左移动一点呢?
方法一:
这个方法简单一些:就把那个图片的UIImageView的宽度,设成比原来大20像素,然后加一句:


imageView.contentMode = UIViewContentModeCenter;

方法二:
写一个类继承UITextField,重写这个方法,然后需要的地方,用你自己写的这个类替换UITextField。

- (CGRect) rightViewRectForBounds:(CGRect)bounds {
 CGRect textRect = [super rightViewRectForBounds:bounds];
 textRect.origin.x -= 10;
 return textRect;
}

方法三:
你再做个底层的rightView。把ImageView加到这个rightView上就行了。随意改变位置了。


A876B1EC-2105-42FA-ABE0-73C26FCC335D.png

此外,textField内文字距左边框距离太近的问题也可参照上面的方法解决:


2B4AA1CA-F074-4E38-81B9-631966CB092D.png

方法一:
写一个类继承UITextField,重写这个方法,然后需要的地方,用你自己写的这个类替换UITextField。
.h文件

- (CGRect)textRectForBounds:(CGRect)bounds;
- (CGRect)editingRectForBounds:(CGRect)bounds;

.m文件

- (CGRect)textRectForBounds:(CGRect)bounds {
    bounds.origin.x += 10;
    return bounds;
}

- (CGRect)editingRectForBounds:(CGRect)bounds {
    bounds.origin.x += 10;
    return bounds;
}

方法二:
可以使用leftView来实现:

textField.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width, height)];
textField.leftViewMode = UITextFieldViewModeAlways;

相关文章

网友评论

  • 横爬介士:浅显易懂,逻辑性强,给作者点个赞

本文标题:UITextfield rightview位置太靠边缘的问题

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