一劝枣、前言
筆者最近一直忙于開(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)就斷層了只壳。