簡體   English   中英

如何正確地在ObjectiveC中子類化?

[英]How to subclass a class in ObjectiveC correctly?

我在名為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];

我將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];

它有效,但我認為這不是正確的方法。 那么如何以正確的方式對類進行子類化?

在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;
}

從技術上講,像您一樣對UITextField進行子類化沒有問題,也許我說的很明顯是因為您告訴我們它有效:D。

但是,如果您打算僅向UITextField添加掩碼,則感覺沒有必要對UITextField進行子類化,可能只是創建輔助方法或類別以將掩碼添加至文本字段,這似乎是一種更清潔的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM