如何在iOS中自定义运行时的子类实现?

时间:2015-09-30 11:36:08

标签: ios objective-c subclass

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>所以任何建议/建议/答案都应该仅基于这个条件:)

1 个答案:

答案 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;