【问题标题】:Setting selected item in UISegmentControl is not working在 UISegmentControl 中设置选定项不起作用
【发布时间】:2014-06-02 13:02:49
【问题描述】:

尝试设置 UISegmentControl 的选定侧,但没有任何反应。

在我的 viewDidLoad 或 viewDidAppear 中,这段代码不会选择一个段?

[self.segmentedControl setSelectedSegmentIndex:[@1 integerValue]];

什么都没有发生?

【问题讨论】:

  • 你登录 self.segmentedControl 看它是否为零?
  • 顺便说一句 - 为什么不简单地传递 1 而不是 [@1 integerValue]
  • 如果为 nil,则确保插座连接正确(假设您使用 Storyboards 或 InterfaceBuilder)。
  • 试试 -(void)awakeFromNib ?
  • 它不是零。 segmentControl 在执行期间存在。 @rmaddy 它是一个占位符,我有返回我想要动态选择的代码的代码。我只是用这种方式对其进行硬编码,以确保它不是我的其他方法。

标签: ios objective-c uisegmentedcontrol


【解决方案1】:

您可以使用代码在 UISegmentControl 中添加和设置选定的选项卡

 NSArray *itemArray = [NSArray arrayWithObjects: @"Top Twenty", @"Dow thirty", @"Favorite", nil];
    segmentedControl = [[UISegmentedControl alloc] initWithItems:itemArray];
    segmentedControl.frame = CGRectMake(15, 80, 300, 30);
    segmentedControl.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [segmentedControl addTarget:self action:@selector(MySegmentControlAction:) forControlEvents: UIControlEventValueChanged];
    segmentedControl.selectedSegmentIndex = 0; //**this line represent selected tab**
    [self.view addSubview:segmentedControl];

【讨论】:

    【解决方案2】:

    我从 Storyboard 中删除了 UISegmentControl 并以编程方式添加它,它现在可以工作了。很奇怪。

    self.segControl.frame = CGRectMake(35, 100, 200, 50);
    self.segControl.segmentedControlStyle = UISegmentedControlStylePlain;
    self.segControl.selectedSegmentIndex = 1;
    
    [self.view addSubview:self.segControl];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-01
      • 1970-01-01
      • 2022-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-23
      相关资源
      最近更新 更多