iOS自定义控件:一个简易的Combobox

iOS自定义控件:一个简易的Combobox_第1张图片
镇楼专用图

代码简单易懂,属于自己练手的代码,还在学习,写的不好,希望勿喷
1、头文件

#import 

NS_ASSUME_NONNULL_BEGIN

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

@protocol WDComboBoxControlDataSource 
@optional
/** < 数据数组 > */
- (NSArray *> *)dataSourceOfColunm;
@required
/** < 标题数组 > */
- (NSArray *)titleOfSection;
@end

@protocol WDComboBoxControlDelegate 

/**
 点击事件
 
 @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  dataSource;
@property (nonatomic, weak) id  delegate;
/** < 背景按钮,可以定义需要的属性 > */
@property (nonatomic, strong) UIButton *backgroundButton;
/** < 内容TableView,也可以定义一些属性 > */
@property (nonatomic, strong) UITableView *tableView;

/**
 初始化方法

 @param height 显示内容高度
 @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、实现文件

#import "WDComboBoxControl.h"

@interface WDComboBoxControl () 

@property (nonatomic, assign) CGFloat viewHeight;
@property (nonatomic, strong) NSArray *> * dataArray;
@property (nonatomic, strong) NSArray * 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 =============== 获取数据源 ===============
- (void)setDataSource:(id)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、导入头文件
#import "WDComboBoxControl.h"
// 2、遵循代理和数据源

// 3、实现方法
#pragma mark =============== WDComBoxControlDataSource ===============
- (NSArray *)titleOfSection;
- (NSArray *> *)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 *)titleOfSection {
    return @[@"安徽省", @"浙江省", @"江苏省", @"安徽省", @"浙江省", @"江苏省"];
}

- (NSArray *> *)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、效果图


iOS自定义控件:一个简易的Combobox_第2张图片
效果图

5、Demo地址(代码都在这里了,就不弄个Demo了,这个可以自定义的地方还有很多,TableView和背景的Button都可以,随心所欲吧!)

你可能感兴趣的:(iOS自定义控件:一个简易的Combobox)