在我的代码中,我使用的UISegmentedControl是一个"按钮",只有一个段,momentary属性设置为YES.在iOS 4之前的SDK版本中,这不是问题,但现在看来iOS 4要求至少有2个段.以下代码抛出异常:
NSArray *titles = [NSArray arrayWithObject:@"Button Title"];
myButton = [[UISegmentedControl alloc] initWithItems:titles];
Run Code Online (Sandbox Code Playgroud)
现在在Interface Builder中,你甚至无法创建一个少于2个段的UISegmentedControl.它在构建时记录以下错误:
"分段控件的段数属性必须大于或等于2".
我有点难过.有没有解决这个问题?我尝试UISegmentedControl使用两个按钮创建一个,然后以编程方式删除一个按钮,因为它不会导致应用程序崩溃.我在iOS 3中获得了一个按钮而在iOS 4中没有任何内容.任何想法?
你试过这个:
[myButton removeAllSegments];
[myButton insertSegmentWithTitle:@"Press this" atIndex:0 animated:NO];
Run Code Online (Sandbox Code Playgroud)
真奇怪.在iOS4模拟器和设备中它仍适用于我(这是我的代码中的一个真正的工作片段):
NSArray *laterContent = [NSArray arrayWithObjects: @"Maybe later", nil];
UISegmentedControl *later = [[UISegmentedControl alloc] initWithItems:laterContent];
CGRect frame = CGRectMake( 20,
98,
self.alert.bounds.size.width/2 - 30,
30);
later.frame = frame;
later.selectedSegmentIndex = -1;
[later addTarget:self action:@selector(laterAction:) forControlEvents:UIControlEventValueChanged];
later.segmentedControlStyle = UISegmentedControlStyleBar;
later.tintColor = [UIColor colorWithRed:130.0f/255.0f green:74.0f/255.0f blue:54.0f/255.0f alpha:0.8f];
later.momentary = YES;
later.alpha = 0.9;
Run Code Online (Sandbox Code Playgroud)