网络知识 娱乐 iOS开发:实现点击常用控件弹出地区选择框(万能方法)

iOS开发:实现点击常用控件弹出地区选择框(万能方法)

前言

在iOS开发中会遇到一些选择选项的需求,而且点击一个控件弹出一个选择框,选择之后展示到前端,然后再把选择的内容传给后台或者做本地存储。这个需求对于大多数开发者来说可以为小儿科,但是作为一个爱记录的程序猿来说相当可贵,所以还是那句话,只分享给有缘人,大牛可以飘过,不喜勿喷请走开。

随后还会分享实现点击UITextField弹出UIDatePicker日期选择器的博文,本篇博文只分享点击控件弹出选择框的方法实现(点击UIButton或者UILabel弹出选择提示框)。

以下案例使用场景:通过点击UITableViewCell,弹出弹框,然后选择地区,最后给cell上面的控件赋值。具体步骤如下所示。

1、声明一个全局属性,来接收选择之后的地区名称参数

@property (strong, nonatomic) NSString *changeRegion; // 地区名称

2、在UITableView的cellForRowAtIndexPath代理方法里面的操作如下

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
 if (indexPath.row == 3)  {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"formCell"];
 if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"formCell"];
        }
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.separatorInset = UIEdgeInsetsMake(0, 5, 0, 5);
        cell.textLabel.text = cellTitles[indexPath.row];
        cell.detailTextLabel.text = _changeRegion;  // 地区赋值
 return cell;
    }
}

3、地区选择弹出框的实现方法

- (void)alterRegion {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    NSString *generalV = NSLocalizedString(@"General Version", nil);
    NSString *America = NSLocalizedString(@"United States", nil);
    NSString *France = NSLocalizedString(@"France", nil);
    NSString *China = NSLocalizedString(@"China", nil);
    NSString *Japan = NSLocalizedString(@"Japan", nil);
    NSString *Taiwan = NSLocalizedString(@"Taiwan", nil);
    NSArray *array = @[generalV, America, France, China, Japan, Taiwan];
 for (int i = 0; i < array.count; i++) {
        [alert addAction:[UIAlertAction actionWithTitle:array[i] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            _changeRegion = array[i];
            [self.tableView reloadData];
        }]];
    }
    NSString *cancel = NSLocalizedString(@"Cancel", nil);
    [alert addAction:[UIAlertAction actionWithTitle:cancel style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}

4、在UITableView的didSelectRowAtIndexPath代理方法里面的操作如下

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
 if (indexPath.row == 3) {
        [self alterRegion]; //调用地区选择弹出框的方法
    }
}

实现之后的效果如下图所示:

这里虽然介绍的是cell的点击事件的弹框处理,其他控件的使用方法类似,比如UIButton、UILabel等控件都可以这样实现地区弹框的选择方法,这里就不再一一介绍。

最后

以上就是本章的全部内容,欢迎关注三掌柜的微信公众号“程序猿by三掌柜”,三掌柜的新浪微博“三掌柜666”,欢迎关注!