我想为我的UITextFields
使用自定义背景。 这工作正常,除了我必须使用UITextBorderStyleNone
使它看起来漂亮。 这会强制文本粘在左边而不进行任何填充。
我可以手动设置填充,使其看起来类似于UITextBorderStyleRoundedRect
除了使用我的自定义背景图像?
#1楼
另一个考虑因素是,如果你有多个UITextField
添加填充,就是为每个文本字段创建一个单独的UIView
- 因为它们无法共享。
#2楼
我基于Nate的解决方案,但后来我发现当你使用leftView / rightView属性时这会导致问题,所以它更好地调整了super的实现,因为它会考虑左/右视图。
- (CGRect)textRectForBounds:(CGRect)bounds {
CGRect ret = [super textRectForBounds:bounds];
ret.origin.x = ret.origin.x + 5;
ret.size.width = ret.size.width - 10;
return ret;
}
- (CGRect)editingRectForBounds:(CGRect)bounds {
return [self textRectForBounds:bounds];
}
#3楼
^这些建议非常适合以编程方式创建界面的人。
但对于我们这些使用Xcode界面构建器的人来说,有两种轻松的方式:
更容易:将UIImageView放在文本字段后面
最简单:将您的边框样式更改为简单的黑色方块(左起第二个选项),然后将图像添加为背景图像。 图像优先于正方形,因此您仍然可以获得正常图像背景所需的填充,而不会实际绘制正方形。
编辑:您也可以使用黑色球体(在IB中选择UITextBox时左侧第三个选项),它不适用于最右侧的“图形球体”样式。
#4楼
向UITextField添加填充的一种好方法是子类化并添加edgeInsets属性。 然后设置edgeInsets,并相应地绘制UITextField。 这也可以使用自定义leftView或rightView集正常运行。
OSTextField.h
#import <UIKit/UIKit.h>
@interface OSTextField : UITextField
@property (nonatomic, assign) UIEdgeInsets edgeInsets;
@end
OSTextField.m
#import "OSTextField.h"
@implementation OSTextField
- (id)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
self.edgeInsets = UIEdgeInsetsZero;
}
return self;
}
-(id)initWithCoder:(NSCoder *)aDecoder{
self = [super initWithCoder:aDecoder];
if(self){
self.edgeInsets = UIEdgeInsetsZero;
}
return self;
}
- (CGRect)textRectForBounds:(CGRect)bounds {
return [super textRectForBounds:UIEdgeInsetsInsetRect(bounds, self.edgeInsets)];
}
- (CGRect)editingRectForBounds:(CGRect)bounds {
return [super editingRectForBounds:UIEdgeInsetsInsetRect(bounds, self.edgeInsets)];
}
@end
#5楼
只需将UITextField子类化为:
@implementation DFTextField
- (CGRect)textRectForBounds:(CGRect)bounds
{
return CGRectInset(bounds, 10.0f, 0);
}
- (CGRect)editingRectForBounds:(CGRect)bounds
{
return [self textRectForBounds:bounds];
}
@end
这会在两侧增加10个点的水平填充。
来源:oschina
链接:https://my.oschina.net/stackoom/blog/3165215