MyTextField是一个UITextField
子类,在文本字段中有额外的边距。
@interface MyTextField : UITextField
@property (nonatomic, assign) bool enableMargin;
- (instancetype) initWithMarginEnable:(BOOL)enable;
@end
@implementation MyTextField
- (CGRect)textRectForBounds:(CGRect)bounds {
if(self.enableMargin) return;
return CGRectInset(bounds, 32.5f, 0);
}
- (CGRect)editingRectForBounds:(CGRect)bounds {
return [self textRectForBounds:bounds];
}
- (instancetype) initWithMarginEnable:(BOOL)enable {
self = [super init];
if(self) {
self.enableMargin = enable;
}
return self;
}
@end
MyTextField *txt = [[MyTextField alloc] init];
但是在我的应用程序中的某些时候,我要求没有任何余量,以保持连续性,并且出于某些原因,我仍然需要在整个应用程序中使用MyTextField
。
MyTextField *txt = [[MyTextField alloc] initWithMarginEnable:YES];
但在我的个人调查中,我意识到textRectForBounds:
方法将始终在MyTextField
获得init
之前调用。
如何制作(或检查)我不想要保证金?我尝试使用自定义init
方法,但仍然会调用textRectForBounds:
。
是的,我的应用程序将支持iOS7>所以任何建议/建议/答案都应该仅基于这个条件:)
答案 0 :(得分:1)
设置setNeedsDisplay
属性后,您必须致电enableMargin
。你不需要单独init
,我会这样做:
@implementation MyTextField
- (CGRect)textRectForBounds:(CGRect)bounds {
if(self.enableMargin) return CGRectInset(bounds, 0, 0);;
return CGRectInset(bounds, 32.5f, 0);
}
- (CGRect)editingRectForBounds:(CGRect)bounds {
return [self textRectForBounds:bounds];
}
-(void)setEnableMargin:(bool)enableMargin {
_enableMargin = enableMargin;
[self setNeedsDisplay];
}
@end
要使用它,您必须致电:
MyTextField *myText = [[MyTextField alloc] init];
myText.frame = // whatever the frame will be
myText.enableMargin = YES;