iOS自定義控件:一個簡易的Combobox

鎮(zhèn)樓專用圖

代碼簡單易懂,屬于自己練手的代碼,還在學(xué)習(xí),寫的不好,希望勿噴
1、頭文件

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

typedef NS_ENUM(NSInteger, WDComboBoxControlDirection) {
    WDComboBoxControlDirectionTop,
    WDComboBoxControlDirectionLeading,
    WDComboBoxControlDirectionTrailing,
    WDComboBoxControlDirectionBottom,
};

@protocol WDComboBoxControlDataSource <NSObject>
@optional
/** < 數(shù)據(jù)數(shù)組 > */
- (NSArray<NSArray<NSString *> *> *)dataSourceOfColunm;
@required
/** < 標題數(shù)組 > */
- (NSArray<NSString *> *)titleOfSection;
@end

@protocol WDComboBoxControlDelegate <NSObject>

/**
 點擊事件
 
 @param indexPath indexPath description
 @param title title description
 @param sourceView sourceView description
 */
- (void)selectedAtIndexPath:(NSIndexPath *)indexPath resultTitle:(NSString *)title fromSourceView:(UIView *)sourceView;
@end

@interface WDComboBoxControl : UIView

@property (nonatomic, weak) id <WDComboBoxControlDataSource> dataSource;
@property (nonatomic, weak) id <WDComboBoxControlDelegate> delegate;
/** < 背景按鈕,可以定義需要的屬性 > */
@property (nonatomic, strong) UIButton *backgroundButton;
/** < 內(nèi)容TableView,也可以定義一些屬性 > */
@property (nonatomic, strong) UITableView *tableView;

/**
 初始化方法

 @param height 顯示內(nèi)容高度
 @param view 參考View
 @return return value description
 */
- (instancetype)initViewWithMaxHeight:(CGFloat)height fromView:(UIView *)view showDirection:(WDComboBoxControlDirection)direction;
/**
 顯示頁面
 */
- (void)showInView;

@end

NS_ASSUME_NONNULL_END

2、實現(xiàn)文件

#import "WDComboBoxControl.h"

@interface WDComboBoxControl () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, assign) CGFloat viewHeight;
@property (nonatomic, strong) NSArray<NSArray<NSString *> *> * dataArray;
@property (nonatomic, strong) NSArray<NSString *> * titleArray;
@property (nonatomic, strong) UIView *sourceView;
@property (nonatomic, assign) WDComboBoxControlDirection direction;
@end

@implementation WDComboBoxControl

#pragma mark =============== 初始化頁面 ===============
- (instancetype)initViewWithMaxHeight:(CGFloat)height fromView:(UIView *)view showDirection:(WDComboBoxControlDirection)direction {
    self = [super init];
    if (self) {
        _viewHeight = height;
        _sourceView = view;
        _direction = direction;
        [self setupSubViewsPropertys];
        [self setupSubViewsConstraints];
    }
    return self;
}

#pragma mark =============== 顯示頁面 ===============
- (void)showInView {
    self.frame = UIScreen.mainScreen.bounds;
    [UIApplication.sharedApplication.delegate.window addSubview:self];
}

#pragma mark =============== 讓頁面消失 ===============
- (void)dismisssView {
    [self removeFromSuperview];
}

#pragma mark =============== 獲取數(shù)據(jù)源 ===============
- (void)setDataSource:(id<WDComboBoxControlDataSource>)dataSource {
    _dataSource = dataSource;
    if (self.dataSource && [self.dataSource respondsToSelector:@selector(dataSourceOfColunm)]) {
        self.dataArray = [self.dataSource dataSourceOfColunm];
    }
    
    if (self.dataArray && [self.dataSource respondsToSelector:@selector(titleOfSection)]) {
        self.titleArray =  [self.dataSource titleOfSection];
    }
    
    [self.tableView reloadData];
}

#pragma mark =============== Add controls, set properties ===============
- (void)setupSubViewsPropertys {
    self.backgroundButton = [[UIButton alloc] init];
    self.backgroundButton.backgroundColor = UIColor.clearColor;
    [self.backgroundButton addTarget:self action:@selector(dismisssView) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.backgroundButton];
    
    self.tableView = [[UITableView alloc] init];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.layer.borderColor = UIColor.lightGrayColor.CGColor;
    self.tableView.layer.borderWidth = 0.5;
    self.tableView.estimatedRowHeight = 45;
    self.tableView.layer.cornerRadius = 5;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    [self addSubview:self.tableView];
}

#pragma mark =============== Setting control layout constraints ===============
- (void)setupSubViewsConstraints {
    self.backgroundButton.frame = UIScreen.mainScreen.bounds;
    
    switch (self.direction) {
        case WDComboBoxControlDirectionBottom:{
            self.tableView.frame = CGRectMake(CGRectGetMinX(self.sourceView.frame),
                                              CGRectGetMaxY(self.sourceView.frame),
                                              self.sourceView.frame.size.width,
                                              self.viewHeight);
        }
            break;
        case WDComboBoxControlDirectionTop:{
            self.tableView.frame = CGRectMake(CGRectGetMinX(self.sourceView.frame),
                                              CGRectGetMaxY(self.sourceView.frame) - self.viewHeight - self.sourceView.frame.size.height,
                                              self.sourceView.frame.size.width,
                                              self.viewHeight);
        }
            break;
        case WDComboBoxControlDirectionLeading:{
            self.tableView.frame = CGRectMake(CGRectGetMinX(self.sourceView.frame) - self.sourceView.frame.size.width,
                                              CGRectGetMinY(self.sourceView.frame),
                                              self.sourceView.frame.size.width,
                                              self.viewHeight);
        }
            break;
        case WDComboBoxControlDirectionTrailing:{
            self.tableView.frame = CGRectMake(CGRectGetMinX(self.sourceView.frame) + self.sourceView.frame.size.width,
                                              CGRectGetMinY(self.sourceView.frame),
                                              self.sourceView.frame.size.width,
                                              self.viewHeight);
        }
            break;
        default:
            break;
    }    
}

#pragma mark =============== UITableViewDelegate, UITableViewDataSource ===============
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return self.titleArray[section];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.dataArray[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    cell.textLabel.text = self.dataArray[indexPath.section][indexPath.row];
    cell.textLabel.numberOfLines = 0;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.delegate && [self.delegate respondsToSelector:@selector(selectedAtIndexPath:resultTitle: fromSourceView:)]) {
        [self.delegate selectedAtIndexPath:indexPath resultTitle:self.dataArray[indexPath.section][indexPath.row] fromSourceView:self.sourceView];
        [self dismisssView];
    }
}
@end

3、使用方法

// 1、導(dǎo)入頭文件
#import "WDComboBoxControl.h"
// 2、遵循代理和數(shù)據(jù)源
<WDComboBoxControlDataSource, WDComboBoxControlDelegate>
// 3、實現(xiàn)方法
#pragma mark =============== WDComBoxControlDataSource ===============
- (NSArray<NSString *> *)titleOfSection;
- (NSArray<NSArray<NSString *> *> *)dataSourceOfColunm;

#pragma mark =============== WDComBoxControlDelegate ===============
- (void)selectedAtIndexPath:(NSIndexPath *)indexPath resultTitle:(NSString *)title fromSourceView:(UIView *)sourceView;


// 下面是實例:
@property (nonatomic, strong) UIButton *button;
@property (nonatomic, strong) UIButton *button2;
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UIButton *button = [[UIButton alloc] init];
    [button setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonShow:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    button.layer.borderColor = UIColor.lightGrayColor.CGColor;
    button.layer.borderWidth = 0.5;
    [button setTitle:@"按鈕" forState:UIControlStateNormal];
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(self.wdNavigationBar.mas_bottom);
        make.width.mas_equalTo(300);

    }];
    self.button = button;
    
    
    UIButton *button2 = [[UIButton alloc] init];
    [button2 setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
    [button2 addTarget:self action:@selector(buttonShow:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button2];
    button2.layer.borderColor = UIColor.lightGrayColor.CGColor;
    button2.layer.borderWidth = 0.5;
    [button2 setTitle:@"按鈕2" forState:UIControlStateNormal];
    button2.bounds = CGRectMake(0, 0, 300, 50);
    button2.center = self.view.center;
    self.button2 = button2;
}
- (void)buttonShow:(UIButton *)sender {
    WDComboBoxControl *view = [[WDComboBoxControl alloc] initViewWithMaxHeight:400 fromView:sender showDirection:WDComboBoxControlDirectionBottom];
    view.dataSource = self;
    view.delegate = self;
    view.backgroundButton.backgroundColor = [UIColor colorWithWhite:0 alpha:0.3];
    [view showInView];
}

#pragma mark =============== WDComBoxControlDataSource ===============
- (NSArray<NSString *> *)titleOfSection {
    return @[@"安徽省", @"浙江省", @"江蘇省", @"安徽省", @"浙江省", @"江蘇省"];
}

- (NSArray<NSArray<NSString *> *> *)dataSourceOfColunm {
    return @[@[@"合肥", @"蕪湖", @"安慶"],
             @[@"南京", @"蘇州", @"無錫"],
             @[@"杭州", @"寧波", @"溫州"],
             @[@"合肥", @"蕪湖", @"安慶"],
             @[@"南京", @"蘇州", @"無錫"],
             @[@"杭州", @"寧波", @"溫州"]];
}

#pragma mark =============== WDComBoxControlDelegate ===============
- (void)selectedAtIndexPath:(NSIndexPath *)indexPath resultTitle:(NSString *)title fromSourceView:(UIView *)sourceView {
    UIButton *sender = (UIButton *)sourceView;
    [sender setTitle:title forState:UIControlStateNormal];
}

4、效果圖


效果圖

5、Demo地址(代碼都在這里了,就不弄個Demo了,這個可以自定義的地方還有很多,TableView和背景的Button都可以,隨心所欲吧?。?/p>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容