如何正确地在ObjectiveC中子类?

时间:2016-09-12 07:04:22

标签: ios objective-c uitextfield subclass

我在文件中写了一个名为login.m

的UITextfield
    _textfield1 = [[UITextField alloc] initWithFrame:CGRectMake(50, 60, self.view.frame.size.width-50*2, 44)];
    _textfield1.placeholder = @"email";
    _textfield1.font = [UIFont systemFontOfSize:14.0f];
    _textfield1.delegate = self;
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:_textfield1.bounds byRoundingCorners:UIRectCornerTopLeft|UIRectCornerTopRight cornerRadii:CGSizeMake(4, 4)];
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.frame = _textfield1.bounds;
    maskLayer.path = maskPath.CGPath;
    _textfield1.layer.mask = maskLayer;
    [self.view addSubview:_textfield1];

和i子类UITextfield,名称为“NewTextField”,NewTextField.h

     #import <UIKit/UIKit.h>
     @interface NewTextField : UITextField
     @end

NewTextField.m

     #import "NewTextField.h"
     @implementation NewTextField
     - (void)setMaskView:(UIView *)maskView {
       UIBezierPath *maskPath = [UIBezierPath   bezierPathWithRoundedRect:maskView.bounds byRoundingCorners:UIRectCornerBottomLeft|UIRectCornerBottomRight cornerRadii:CGSizeMake(4, 4)];
       CAShapeLayer *maskLayer = [CAShapeLayer layer];
       maskLayer.frame = maskView.bounds;
       maskLayer.path = maskPath.CGPath;
       maskView.layer.mask = maskLayer;
    }
    @end

在文件login.m中,我更新代码

   _textfield1 = [[NewTextField alloc] initWithFrame:CGRectMake(50, 60, self.view.frame.size.width-50*2, 44)];
   _textfield1.placeholder = @"email";
   _textfield1.font = [UIFont systemFontOfSize:14.0f];
   _textfield1.delegate = self;
   [_textfield1 setMaskView:_textfield1];
   [self.view addSubview:_textfield1];

它有效,但我不认为这是正确的方法。那么我怎么能以正确的方式对一个类进行子类化呢?

2 个答案:

答案 0 :(得分:0)

在NewTextField.m而不是 - (void)setMaskView:(UIView *)maskView写一个初始化方法,如下所示,

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        UIBezierPath *maskPath = [UIBezierPath   bezierPathWithRoundedRect:self.bounds byRoundingCorners:UIRectCornerBottomLeft|UIRectCornerBottomRight cornerRadii:CGSizeMake(4, 4)];
        CAShapeLayer *maskLayer = [CAShapeLayer layer];
        maskLayer.frame = self.bounds;
        maskLayer.path = maskPath.CGPath;
        self.layer.mask = maskLayer;
    }
    return self;
}

答案 1 :(得分:0)

从技术上讲,像你所做的那样对UITextField进行子类化是没有问题的,也许我说的很明显,因为你告诉我们它有效:D。

但是如果你打算只是为UITextField添加一个掩码,那么就不必为UITextField创建子类,也许只需要创建辅助方法或类别来将掩码添加到文本字段中,这似乎是一种更清晰的方法。