如果您以编程方式创建它,您可以像这样延迟加载它:
@interface ExampleViewController : UIViewController
@property (nonatomic, strong) UISegmentedControl *segmentedControl;
- (void)segmentedControlClicked:(UISegmentedControl *)segmentedControl;
@end
@implementation ExampleViewController
- (UISegmentedControl *)segmentedControl
{
if (!_segmentedControl)
{
NSArray *items = @[@"First", @"Second", @"Third"];
_segmentedControl = [[UISegmentedControl alloc] initWithItems:items];
[_segmentedControl addTarget:self
action:@selector(segmentedControlClicked:)
forControlEvents:UIControlEventValueChanged];
[_segmentedControl setSelectedSegmentIndex:0]; // Set Default selection
CGRect frame = _segmentedControl.frame;
frame.origin = CGPointMake(0.0f, 0.0f); // Move to wherever you need it
[self.view addSubview:_segmentedControl];
}
return _segmentedControl;
}
- (void)segmentedControlClicked:(UISegmentedControl *)segmentedControl
{
// Whatever your code is goes here...
}
@end
如果您希望最初也调用一个方法,您可以在您的viewDidLoad:
方法中调用它,如下所示:
- (void)viewDidLoad
{
[self.segmentedControl setSelectedSegmentIndex:0]; // Set desired default index (optional if set in lazy load as shown above)
[self segmentedControlClicked:self.segmentedControl];
}
因此,这将模拟对所需默认索引的点击。
小心将上面的内容放入viewDidAppear:
(如果你真的想的话,你可以这样做),因为只要视图出现在前面,就会调用这个方法(例如,如果这个视图控制器呈现一个模态视图控制器,一旦模态被解除,这个视图控制器的viewDidAppear:
方法将被调用)。
干杯!