iOS-8及更高版本 – UIAlertController中的UITableView
我知道如何通过使用像UITableView
accessoryView
UIAlertView
添加任何Custom UI
,但我现在好奇,如果我们仍然有select添加Custom UI
内UIAlertController
,我想要的是一个UIAlertController
内清醒的UIAlertController
。
礼貌的StackOverflow用户我能够做这个任务。
这是我的代码:
UIViewController *controller = [[UIViewController alloc]init]; UITableView *alertTableView; CGRect rect; if (array.count < 4) { rect = CGRectMake(0, 0, 272, 100); [controller setPreferredContentSize:rect.size]; } else if (array.count < 6){ rect = CGRectMake(0, 0, 272, 150); [controller setPreferredContentSize:rect.size]; } else if (array.count < 8){ rect = CGRectMake(0, 0, 272, 200); [controller setPreferredContentSize:rect.size]; } else { rect = CGRectMake(0, 0, 272, 250); [controller setPreferredContentSize:rect.size]; } alertTableView = [[UITableView alloc]initWithFrame:rect]; alertTableView.delegate = self; alertTableView.dataSource = self; alertTableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero]; [alertTableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine]; [alertTableView setTag:kAlertTableViewTag]; [controller.view addSubview:alertTableView]; [controller.view bringSubviewToFront:alertTableView]; [controller.view setUserInteractionEnabled:YES]; [alertTableView setUserInteractionEnabled:YES]; [alertTableView setAllowsSelection:YES]; UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Title" message:@"Message" preferredStyle:UIAlertControllerStyleAlert]; [alertController setValue:controller forKey:@"contentViewController"]; UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) { }]; [alertController addAction:cancelAction]; [self presentViewController:alertController animated:YES completion:nil];
UIViewController *tempViewController = [[UIViewController alloc] init]; tempViewController.view.backgroundColor = [UIColor redColor]; [alertController setValue:tempViewController forKey:@"contentViewController"];
UIAlertController
代码将在alert视图中显示一个红色的视图,现在你可以很容易地把一个UITableView
放在UIViewController
UIAlertController
定制;)
这里是@Syed Ali Salman在Swift中简化的答案 :
let alertController = UIAlertController(title: "The Title", message: "Here's a message.", preferredStyle: .Alert) let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in // ... } alertController.addAction(cancelAction) let okAction = UIAlertAction(title: "OK", style: .Default) { (action) in // ... } alertController.addAction(okAction) let tableViewController = UITableViewController() tableViewController.preferredContentSize = CGSize(width: 272, height: 176) // 4 default cell heights. alertController.setValue(tableViewController, forKey: "contentViewController") yourTopViewController().presentViewController(alertController, animated: true) { // ... }