我做了一個簡約的示範項目,你這說明如何完成你想要的。
這是相關代碼:
@interface HASTableViewController()
@property (strong, nonatomic) UISegmentedControl *sortButton;
@property (copy, nonatomic) NSArray *dataSource1;
@property (copy, nonatomic) NSArray *dataSource2;
@property (copy, nonatomic) NSArray *dataSource3;
@end
@implementation HASTableViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Create the segmented control
self.sortButton = [[UISegmentedControl alloc] initWithItems:@[@"First", @"Second", @"Hide me"]];
[self.sortButton addTarget:self action:@selector(switchDataInTableView) forControlEvents:UIControlEventValueChanged];
self.navigationItem.titleView = self.sortButton;
self.sortButton.selectedSegmentIndex = 0;
// We set the title you want to show when the segmented control is "hidden"
self.navigationItem.title = @"Sort Button is nil.";
// Setup a data source
self.dataSource1 = @[@"First", @"First", @"First", @"First", @"First", @"First", @"First", @"First", @"First", @"First", @"First"];
// and another one
self.dataSource2 = @[@"Second", @"Second", @"Second", @"Second", @"Second"];
// Create a third datasource which contains both arrays
NSMutableArray *tempDataSourceArray3 = [[NSMutableArray alloc] initWithArray:self.dataSource1];
[tempDataSourceArray3 addObjectsFromArray:self.dataSource2];
self.dataSource3 = tempDataSourceArray3;
}
- (void)switchDataInTableView {
// Reload the table view.
// tableView:cellForRowAtIndexPath decides which datasource to show
[self.tableView reloadData];
// If it is "Hide it" we hide
if (self.sortButton.selectedSegmentIndex == 2) self.navigationItem.titleView = nil;
}
#pragma mark - UITableView Data Source Methods
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// We use the standard cell
UITableViewCell *tableViewCell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
// If "First" is selected we want the text to be taken fromt the dataSource1 array
tableViewCell.textLabel.text = self.sortButton.selectedSegmentIndex == 0 ? self.dataSource1[indexPath.item] : self.sortButton.selectedSegmentIndex == 1 ? self.dataSource2[indexPath.item] : self.dataSource3[indexPath.item];
return tableViewCell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// return number of rows
return self.sortButton.selectedSegmentIndex == 0 ? self.dataSource1.count : self.sortButton.selectedSegmentIndex == 1 ? self.dataSource2.count : self.dataSource3.count;
}
@end
Download it here
來源
2013-11-24 13:37:59
HAS
檢查IBOutlet中! – Vinodh
@property(強,非原子)IBOutlet UISegmentedControl * sortButton;我已經添加了這個:) – nejc
請使用'YES'和'NO'代替'TRUE'和'FALSE'。 ;)因爲'self.title = @「whatever」;我們需要一些關於佈局是如何工作的信息和/或代碼;''實際上應該可以工作。 – HAS