我的表中有9个部分(它们从数组中拉出)。在4个部分中,我将有1行拉起一个UIPickerView。在这些部分的5个部分中,我将需要5个不同的UISegmentedControls,并具有不同数量的选择选项(2-5个选项)。有人对我有什么实施建议吗?
是否应该为每个UISegmentedControl构建单独的xib文件?我觉得会有/应该有一个更好的方法来做到这一点。
任何帮助,将不胜感激!
最佳答案
您将表结构放在NSArray中,因此建议您为应该具有分段控件的每一行创建一个NSDictionary,并将其添加到表结构NSArray中
您将在字典中需要三个对象。一个标题,一个带有段名称的NSArray,您需要一个用于设置和获取所选索引的键。
我为某些应用程序中的设置viewcontroller做了类似的事情。这是NSDictionary的样子:
[NSDictionary dictionaryWithObjectsAndKeys:
@"Value of Foo", kSettingsLabel, // for the textLabel
[UISegmentedControl class], kSettingsView, // which UIControl
@"foo", kSettingsKey, // the key for setValue:forKey: and valueForKey:
[NSArray arrayWithObjects: @"Green", @"Round", @"Auto",nil], kSettingsValue, // the titles of the segments
nil]
这是我在表格视图中设置UISegmentedControls的方式:
NSDictionary *dictionary = [[self.dataSourceArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
// omitted: check in the dictionary which cell we need... (I wrote it that it can use almost all UIControls)
// omitted: dequeue a cell with a UISegmentedControl ...
// configure cell:
NSArray *segmentTitles = [dictionary objectForKey:kSettingsValue];
UISegmentedControl *segment = (UISegmentedControl *)[cell viewWithTag:kTagSegment];
[segment removeAllSegments];
for (NSString *segmentName in segmentTitles) {
// if index is higher than number of indexes title is inserted at last available index.
// so first object in array is placed at first position in segmentcontrol
[segment insertSegmentWithTitle:segmentName atIndex:1000 animated:NO];
}
[segment setSelectedSegmentIndex:[[self valueForKey:[dictionary valueForKey:kSettingsKey]] intValue]];
//omitted: setup cell title ... and return cell
UISegmentedControl连接到一个值更改操作,如下所示:
NSIndexPath *indexPath = [self.settingsTable indexPathForCell:(UITableViewCell *)[[sender superview] superview]];
if (indexPath == nil)
return;
NSDictionary *dictionary = [[self.dataSourceArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
if ([sender isKindOfClass:[UISegmentedControl class]]) {
[self setValue:[NSNumber numberWithInt:((UISegmentedControl *)sender).selectedSegmentIndex] forKey:[dictionary valueForKey:kSettingsKey]];
}
当然,您还需要指定密钥的设置器和获取器:
- (NSNumber *)foo {
return [NSNumber numberWithInt:someValue];
}
- (void)setFoo:(NSNumber *)n {
someValue = [n intValue];
}
您可以合成它们,但是我想在我的班级而不是NSNumbers中使用int值,所以我自己写了setter和getter。
这样做的最大优点是它是完全动态的。如果要重新排列单元格,只需在数组中移动它们即可(我使用plist使其变得更加容易)。
第一次使用时,它有点复杂,但是很快就会很清楚。而且,您不想在类界面中使用五个不同的.xib和五个不同的UISegmentedControls。