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
的 get init
之前调用。
我如何确定(或检查)我是否不需要 margin ?我已经尝试使用自定义 init
方法,但它仍然调用 textRectForBounds:
。
是的,我的应用程序将支持 iOS7 > 所以任何建议/建议/答案都应该仅基于此条件:)
最佳答案
设置 enableMargin
属性后,您必须调用 setNeedsDisplay
。您不需要单独创建一个 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;
关于ios - 如何在 iOS 运行时自定义子类实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32865081/