我希望“自动化”对segmentController的点击为0.
我的基于tabBar的应用程序在ViewDidAppear方法的选项卡中有多个segmentControllers,我想自动让它“点击”第一个分段控制器。
if (segmentController.selectedSegmentIndex == 0) {
//stuff here
}
if (segmentController.selectedSegmentIndex == 1) {
//stuff here
}
有谁知道我怎么做到这一点?谢谢!
答案 0 :(得分:1)
在selectedSegmentIndex
(或UISegmentedControl
)方法的viewDidAppear
上设置viewDidLoad
属性。
self.segmentedController.selectedSegemntIndex = 1;
答案 1 :(得分:1)
如果你是以编程方式创建它,你可以像这样延迟加载它:
@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:
方法。
干杯!