ios - 如何在 iOS 运行时自定义子类实现?

标签 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 的 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/

相关文章:

iphone - 向现有项目添加单元测试?

ios - Xcode 与 uncrustify : how to align function declaration to colons?

c++ - 在 C++ 中选择随机子类

ios - 每个 Xcode iOS 模拟器操作系统版本的唯一 NSUserDefaults?

ios - 在后台运行 URL 请求

ios - NSURLConnection 接收数据的百分比

objective-c - Swift: "Mapper is not a type",在 swift 和 Objective C 中为数组使用自定义映射类

objective-c - "Use of unresolved identifier"错误,但我有在框架中声明的标识符

java - 将 Builder 扩展/子类化到直接子级之外

xcode - 在 Swift 中子类化 UIViewController 的样板代码