我将imageView设置为文本字段的右视图。这是我的代码:
UITextField *textField = [[UITextField alloc]initWithFrame:controlFrame];
[textField setBorderStyle:UITextBorderStyleRoundedRect];
[textField setBackgroundColor:[UIColor whiteColor]];
CGRect imageViewFrame = CGRectMake(controlFrame.origin.x + controlFrame.size.width - 20,controlFrame.origin.y, 15.0,controlFrame.size.height-10);
UIImage *image = [UIImage imageNamed:@"arrow.png"];;
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
[imageView setBackgroundColor:[UIColor clearColor]];
[imageView setFrame:imageViewFrame];
[textField setRightViewMode:UITextFieldViewModeAlways];
textField.rightView = imageView;
它在iOS 6.1设备
但在iOS 7设备中
任何解决方案?
提前致谢
答案 0 :(得分:3)
我自己正在研究并使用这个解决方案:
- (CGRect) rightViewRectForBounds:(CGRect)bounds {
CGRect textRect = [super rightViewRectForBounds:bounds];
textRect.origin.x -= 10;
return textRect;
}
这会将图像从右侧移动10而不是将图像挤压到iOS 7中的边缘。
此外,这是在UITextField的子类中,可以通过以下方式创建:
创建一个新文件,它是UITextField的子类,而不是默认的NSObject 添加一个名为 - (id)的新方法initWithCoder:(NSCoder *)编码器来设置图像
- (id)initWithCoder:(NSCoder*)coder {
self = [super initWithCoder:coder];
if (self) {
self.clipsToBounds = YES;
[self setRightViewMode:UITextFieldViewModeUnlessEditing];
self.leftView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"textfield_edit_icon.png"]];
}
return self;
}
您可能需要导入#import
在
上面添加rightViewRectForBounds方法在Interface Builder中,单击要子类化的TextField,并将class属性更改为此新子类的名称
答案 1 :(得分:0)
还有另一个更快的选项,无需子类化你的uitextfield。有一个例子
UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 10, 6)];
[imageView setImage:[UIImage imageNamed:@"grey_filter.png"]];
UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 6)];
[paddingView addSubview:imageView];
使用填充创建比图像大的视图。添加您的UIImageView,然后将其作为左/右视图放在文本字段中。