2016-09-12 9 views
0

ObjectiveCでクラスを正しくサブクラス化する方法は?

 #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 
NewTextField.m

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

NewTextField.h

、私はlogin.m

_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]; 

というファイルにコードでのUITextFieldを書き、i 'はNewTextField' の名前でのUITextFieldのサブクラスを作成ファイルin 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]; 

それは動作しますが、私は正しい方法ではないと思います。だから私はどのようにして正しい方法でクラスをサブクラス化できますか? NewTextField.mで

+0

なぜそれが間違っていると思いますか?あなたは何の問題を抱えていますか? – Avi

+1

コードを更新した後、 '_textfield1 = [[NewTextField alloc] ....'ではないでしょうか? – Tj3n

+0

ここで@Aviはとても奇妙です。[_textfield1 setMaskView:_textfield1]; – yeleko

答えて

0

の代わりに、 - (無効)setMaskView:(UIViewの*)は、あなたがやったように

- (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; 
} 
0

は、技術的にはサブクラスのUITextFieldに問題が多分、存在しない、怒鳴るよう初期化メソッドを記述しmaskViewあなたが私たちにそれが働いていると言ったので私は明白です。

しかし、UITextFieldにマスクを追加するだけであれば、UITextFieldをサブクラス化する必要はなく、ヘルパーメソッドやカテゴリを作成してマスクをテキストフィールドに追加することもできます。

関連する問題