How do I switch UIsegmentedControll programmatically?

落爺英雄遲暮 提交于 2020-01-30 18:19:27

问题


How do I switch UISegmentedControll programmatically ?


回答1:


The selectedSegmentIndex property identifies the selected segment of a UISegmentedControl. Set this property to the any valid segment index, or UISegmentedControlNoSegment (-1) to turn off the current selection.

// select the first segment
segmented.selectedSegmentIndex = 0;

// turn off the current selection
segmented.selectedSegmentIndex = UISegmentedControlNoSegment;



回答2:


Alternatively, after you have changed the selectedSegmentIndex call 'sendActionsForControlEvents:' for example

segmentedControl.selectedSegmentIndex = 0

[segmentedControl sendActionsForControlEvents:UIControlEventValueChanged];



回答3:


@jmstone response, true, this action will not invoke the valueChanged event for this control.

One way to overcome this is to just call the function yourself:

segmentedControl.selectedSegmentIndex = 3;
[self valueChangedMethod:segmentedControl];

This will call:

- (void)valueChangedMethod:(UISegmentedControl *)segmentedControl
{
    //continue your code here...
}



回答4:


In Swift:

segmentedControl.selectedSegmentIndex = 1

Swift 2:

segmentedControl.sendActionsForControlEvents(UIControlEvents.ValueChanged)

Swift 3:

segmentedControl.sendActions(for: UIControlEvents.valueChanged)



回答5:


I've had a similar problem where the segmented control wasn't changing. I was calling "selectedSegmentIndex", etc too early. Once I called it after "viewDidLoad" was called then everything was fine again.




回答6:


@arcady bob answer was the one that did the trick for me.

I just post an updated version for Swift 5:

yourSegmentedControl.selectedSegmentIndex = 0
yourSegmentedControl.sendActions(for: UIControlEvents.valueChanged)

If you use just the first line, the segmented will react accordingly graphically, but your IBAction associated with the segmented control won't be called. In a few words: the second line is like tapping on the segmented control. This is what I needed and what I was missing.



来源:https://stackoverflow.com/questions/5273775/how-do-i-switch-uisegmentedcontroll-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!