当UITextView在xib中时,向UITextView添加类别并覆盖它的init函数

时间:2014-06-04 06:33:58

标签: ios objective-c uitextview xib objective-c-category

我无法拦截在xib文件中创建时调用的init函数。

我想在创建它时为其添加边框,这样我就不需要手动添加它。

·H:

#import <UIKit/UIKit.h>

@interface UITextView (FITAddBorderline)
- (id) init;
- (id) initWithFrame:(CGRect)frame;
@end

的.m:

#import "UITextView+FITAddBorderline.h"

@implementation UITextView (FITAddBorderline)

- (id) init
{
    self = [super init];
    if (self) {
        [self addBorderline];
    }
    return self;
}

- (id) initWithFrame:(CGRect)frame {

    self = [super init];
    if (self) {
        self.frame = frame;
        [self addBorderline];
    }
    return self;
}

- (void) addBorderline {

    //To make the border look very close to a UITextField
    [self.layer setBorderColor:[[[UIColor grayColor] colorWithAlphaComponent:0.5] CGColor]];
    [self.layer setBorderWidth:2.0];

    //The rounded corner part, where you specify your view's corner radius:
    self.layer.cornerRadius = 5;
    self.clipsToBounds = YES;
}

@end

2 个答案:

答案 0 :(得分:2)

使用initWithCoder:

初始化来自NIB的视图
- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];

    if (self)
    {
        [self addBorderline];
    }

    return self;
}

作为旁注,我建议改变你正在做的事情并使用子类而不是类别。你可以让自己在一个类别中覆盖一些方法。 See more info here.

答案 1 :(得分:2)

您只需要实施awakeFromNib方法:

-(void)awakeFromNib

{
    [super awakeFromNib];
    [self addBorderline];
}