iOS-關(guān)于繼承、分類

一劝枣、前言

筆者最近一直忙于開(kāi)發(fā)業(yè)務(wù)需求汤踏,頻繁的使用著繼承、分類舔腾,切身的體會(huì)到很多需求用這兩種方案都可以解決溪胶,這就面臨著幸福二選一的問(wèn)題了!但越到后面稳诚,越能感覺(jué)到其明顯的區(qū)別哗脖,于是有所感~


繼承與分類

二、需求簡(jiǎn)要

iOS 時(shí)間選擇器(UIDatePicker)大家都有用過(guò)吧,很方便對(duì)吧才避,那性別選擇橱夭、省市區(qū)選擇、付款方式選擇等功能桑逝,我們?nèi)绾螌?shí)現(xiàn)類似的效果呢棘劣?用UIPickerView實(shí)現(xiàn)單選擇功能,就能實(shí)現(xiàn)類似的用戶體驗(yàn)楞遏。

三茬暇、應(yīng)用場(chǎng)景

筆者最近遇到的開(kāi)發(fā)需求是產(chǎn)品的屬性選擇,比如我們現(xiàn)在要發(fā)起訂單(我們可以類比一下淘寶)寡喝,選擇了佳得樂(lè)而钞,這時(shí)候我們還要選擇口味(藍(lán)莓、鮮橙拘荡、哈密瓜等)臼节,然后還可以選擇凈含量等。

demo

四珊皿、代碼實(shí)現(xiàn)

由于在實(shí)際開(kāi)發(fā)中网缝,通常都是與UITextField聯(lián)合實(shí)現(xiàn)的,筆者就選擇UITextField為最小顆粒度蟋定,對(duì)其進(jìn)行處理粉臊。

  • 1.使用繼承方案

LYTextField.h

#import <UIKit/UIKit.h>

@interface LYTextField : UITextField

@property (nonatomic, strong) NSArray *dataArr;

@end

LYTextField.m

#import "LYTextField.h"

@interface LYTextField ()
<UIPickerViewDelegate, UIPickerViewDataSource>

@property (nonatomic, weak) UIPickerView *pickerView;

@end

@implementation LYTextField

- (instancetype)init {
    self = [super init];
    if (self) {
        [self configFoundation];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self configFoundation];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self configFoundation];
    }
    return self;
}

- (void)configFoundation {
    
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
    
    UIView *optionView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, 44)];
    optionView.backgroundColor = [UIColor orangeColor];

    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancelBtn setFrame:CGRectMake(0, 0, 70, 44)];
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancelBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [cancelBtn.titleLabel setFont:[UIFont systemFontOfSize:17.0]];
    [cancelBtn addTarget:self action:@selector(onClickCancelBtn) forControlEvents:UIControlEventTouchUpInside];
    [optionView addSubview:cancelBtn];
    
    UIButton *finishBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [finishBtn setFrame:CGRectMake(screenWidth - 70, 0, 70, 44)];
    [finishBtn setTitle:@"完成" forState:UIControlStateNormal];
    [finishBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [finishBtn.titleLabel setFont:[UIFont systemFontOfSize:17.0]];
    [finishBtn addTarget:self action:@selector(onClickFinishBtn) forControlEvents:UIControlEventTouchUpInside];
    [optionView addSubview:finishBtn];
    
    UILabel *titleL = [[UILabel alloc]initWithFrame:CGRectMake(screenWidth / 2.0 - 75.0, 0, 150, 44)];
    titleL.textAlignment = NSTextAlignmentCenter;
    titleL.text = @"請(qǐng)選擇類型";
    [optionView addSubview:titleL];
    
    self.inputAccessoryView = optionView;
    
    UIPickerView *pickerView = [[UIPickerView alloc] init];
    pickerView.dataSource = self;
    pickerView.delegate = self;
    pickerView.backgroundColor = [UIColor whiteColor];
    self.pickerView = pickerView;
    self.inputView = pickerView;
}

- (void)onClickCancelBtn {
    [self resignFirstResponder];
}

- (void)onClickFinishBtn {
    
    NSInteger index = [self.pickerView selectedRowInComponent:0];
    if (index < self.dataArr.count) {
        self.text = self.dataArr[index];
    }
    [self resignFirstResponder];
}

#pragma mark - Picker view data source && delegate
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return self.dataArr.count;
}

- (NSString *)pickerView:(UIPickerView *)pickerView
             titleForRow:(NSInteger)row
            forComponent:(NSInteger)component {
    
    if (row < self.dataArr.count) {
        return self.dataArr[row];
    }
    
    return @"";
}
@end
  • 2.使用分類方案

UITextField+Tool.h

#import <UIKit/UIKit.h>

typedef void(^DidSelectedBlock)(NSString *value);

@interface UITextField (Tool)
<UIPickerViewDelegate, UIPickerViewDataSource>

- (void)configSigleChoiceWith:(NSArray *)preData completion:(DidSelectedBlock)completion;

- (void)configValue:(NSString *)value;

@end

UITextField+Tool.m

#import "UITextField+Tool.h"
#import <objc/runtime.h>

@interface UITextField ()

@property (nonatomic, strong) NSArray *choiceData;

@property (nonatomic, copy) DidSelectedBlock didSelectedBlock;

@end

NSString *const KeyChoiceData = @"KeyChoiceData";
NSString *const KeyDidSelectedBlock = @"KeyDidSelectedBlock";

@implementation UITextField (Tool)

- (NSArray *)choiceData {
    return objc_getAssociatedObject(self, &KeyChoiceData);
}

- (void)setChoiceData:(NSArray *)choiceData {
    objc_setAssociatedObject(self, &KeyChoiceData, choiceData, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (DidSelectedBlock)didSelectedBlock {
    return objc_getAssociatedObject(self, &KeyDidSelectedBlock);
}

- (void)setDidSelectedBlock:(DidSelectedBlock)didSelectedBlock {
    objc_setAssociatedObject(self, &KeyDidSelectedBlock, didSelectedBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (void)configSigleChoiceWith:(NSArray *)preData completion:(DidSelectedBlock)completion {
    self.choiceData = [preData mutableCopy];
    self.didSelectedBlock = completion;
    
    [self setSelectedList];
}

- (void)configValue:(NSString *)value {
    self.text = value;
    if (self.didSelectedBlock) {
        self.didSelectedBlock(value);
    }
    if (value.length == 0) {
        return;
    }
    for (NSInteger i = 0; i < self.choiceData.count; i ++) {
        NSString *itemStr = self.choiceData[I];
        if ([value isEqualToString:itemStr]) {
            UIPickerView *pickerView = (UIPickerView *)self.inputView;
            [pickerView selectRow:i inComponent:0 animated:YES];
            break;
        }
    }
}

- (void)setSelectedList {
    
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
    
    UIView *optionView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, 44)];
    optionView.backgroundColor = [UIColor orangeColor];
    
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancelBtn setFrame:CGRectMake(0, 0, 70, 44)];
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancelBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [cancelBtn.titleLabel setFont:[UIFont systemFontOfSize:17.0]];
    [cancelBtn addTarget:self action:@selector(onClickCancelBtn) forControlEvents:UIControlEventTouchUpInside];
    [optionView addSubview:cancelBtn];
    
    UIButton *finishBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [finishBtn setFrame:CGRectMake(screenWidth - 70, 0, 70, 44)];
    [finishBtn setTitle:@"完成" forState:UIControlStateNormal];
    [finishBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [finishBtn.titleLabel setFont:[UIFont systemFontOfSize:17.0]];
    [finishBtn addTarget:self action:@selector(onClickFinishBtn) forControlEvents:UIControlEventTouchUpInside];
    [optionView addSubview:finishBtn];
    
    UILabel *titleL = [[UILabel alloc]initWithFrame:CGRectMake(screenWidth / 2.0 - 75.0, 0, 150, 44)];
    titleL.textAlignment = NSTextAlignmentCenter;
    titleL.text = @"請(qǐng)選擇類型";
    [optionView addSubview:titleL];
    
    self.inputAccessoryView = optionView;
    
    UIPickerView *pickerView = [[UIPickerView alloc] init];
    pickerView.dataSource = self;
    pickerView.delegate = self;
    pickerView.backgroundColor = [UIColor whiteColor];
    
    self.inputView = pickerView;
}

#pragma mark - Actions

- (void)onClickCancelBtn {
    [self resignFirstResponder];
}

- (void)onClickFinishBtn {
    
    UIPickerView *pickerView = (UIPickerView *)self.inputView;
    
    NSInteger index = [pickerView selectedRowInComponent:0];
    
    if (index < self.choiceData.count) {
        
        [self configValue:self.choiceData[index]];
    }
    [self resignFirstResponder];
}

#pragma mark - Picker view data source && delegate
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return self.choiceData.count;
}

- (NSString *)pickerView:(UIPickerView *)pickerView
             titleForRow:(NSInteger)row
            forComponent:(NSInteger)component {
    
    if (row < self.choiceData.count) {
        return self.choiceData[row];
    }
    
    return @"";
}

@end
  • 3.使用代碼
- (void)configTextFieldDemo {
    
    CGFloat screenWidth = self.view.bounds.size.width;
    
    LYTextField *textField1 = [[LYTextField alloc] init];
    textField1.bounds = CGRectMake(0, 0, 200, 44);
    textField1.borderStyle = UITextBorderStyleRoundedRect;
    textField1.center = CGPointMake(screenWidth/2, 100);
    textField1.placeholder = @"請(qǐng)選擇口味";
    textField1.dataArr = @[@"鮮橙", @"哈密瓜", @"藍(lán)莓"];
    [self.view addSubview:textField1];
    
    UITextField *textField2 = [[UITextField alloc] init];
    textField2.bounds = CGRectMake(0, 0, 200, 44);
    textField2.borderStyle = UITextBorderStyleRoundedRect;
    textField2.center = CGPointMake(screenWidth/2, 200);
    textField2.placeholder = @"請(qǐng)選擇凈含量";
    [self.view addSubview:textField2];
    NSArray *dataArr = @[@"250 mL", @"500 mL", @"1000 mL"];
    [textField2 configSigleChoiceWith:dataArr completion:nil];
}

五、寫在最后

  • 上例中驶兜,分類明顯的優(yōu)勢(shì)在于可以孤立存在扼仲,也是最干凈的編碼。其實(shí)就是在一個(gè)對(duì)象的基礎(chǔ)上增加額外的功能形成另外一個(gè)對(duì)象抄淑。
  • 關(guān)于繼承毫無(wú)疑問(wèn)最大的優(yōu)點(diǎn)是代碼復(fù)用屠凶。但是很多時(shí)候繼承也可能會(huì)被無(wú)止境的濫用,造成代碼結(jié)構(gòu)散亂肆资,后期維護(hù)困難等矗愧,其中有可能帶來(lái)最大的問(wèn)題是高耦合,依賴性太強(qiáng)郑原。
  • 實(shí)際開(kāi)發(fā)中如果繼承超過(guò)2層的時(shí)候唉韭,就要慎重了,因?yàn)檫@可能是濫用繼承的開(kāi)始犯犁。
  • 分類是一種平行的架構(gòu)属愤,相互獨(dú)立存在,可移植性強(qiáng)酸役,繼承是縱向的架構(gòu)住诸,相互依賴驾胆,缺一個(gè),整個(gè)架構(gòu)就斷層了只壳。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末俏拱,一起剝皮案震驚了整個(gè)濱河市暑塑,隨后出現(xiàn)的幾起案子吼句,更是在濱河造成了極大的恐慌,老刑警劉巖事格,帶你破解...
    沈念sama閱讀 219,039評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件惕艳,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡驹愚,警方通過(guò)查閱死者的電腦和手機(jī)远搪,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,426評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)逢捺,“玉大人谁鳍,你說(shuō)我怎么就攤上這事〗偻” “怎么了倘潜?”我有些...
    開(kāi)封第一講書人閱讀 165,417評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)志于。 經(jīng)常有香客問(wèn)我涮因,道長(zhǎng),這世上最難降的妖魔是什么伺绽? 我笑而不...
    開(kāi)封第一講書人閱讀 58,868評(píng)論 1 295
  • 正文 為了忘掉前任养泡,我火速辦了婚禮,結(jié)果婚禮上奈应,老公的妹妹穿的比我還像新娘澜掩。我一直安慰自己,他們只是感情好杖挣,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,892評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布输硝。 她就那樣靜靜地躺著,像睡著了一般程梦。 火紅的嫁衣襯著肌膚如雪点把。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書人閱讀 51,692評(píng)論 1 305
  • 那天屿附,我揣著相機(jī)與錄音郎逃,去河邊找鬼。 笑死挺份,一個(gè)胖子當(dāng)著我的面吹牛褒翰,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 40,416評(píng)論 3 419
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼优训,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼朵你!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起揣非,我...
    開(kāi)封第一講書人閱讀 39,326評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤抡医,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后早敬,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體忌傻,經(jīng)...
    沈念sama閱讀 45,782評(píng)論 1 316
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,957評(píng)論 3 337
  • 正文 我和宋清朗相戀三年搞监,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了水孩。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,102評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡琐驴,死狀恐怖俘种,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情绝淡,我是刑警寧澤宙刘,帶...
    沈念sama閱讀 35,790評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站够委,受9級(jí)特大地震影響荐类,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜茁帽,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,442評(píng)論 3 331
  • 文/蒙蒙 一玉罐、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧潘拨,春花似錦吊输、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 31,996評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至琅束,卻和暖如春扭屁,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背涩禀。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 33,113評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工料滥, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人艾船。 一個(gè)月前我還...
    沈念sama閱讀 48,332評(píng)論 3 373
  • 正文 我出身青樓葵腹,卻偏偏與公主長(zhǎng)得像高每,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子践宴,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,044評(píng)論 2 355