简体   繁体   中英

How can I set the default state of a UISegmentedControl?

Is there a way to set the starting selected segment in a UISegmentedControl in Interface Builder, or do I have to do it in the code? If it's in the code, is viewDidLoad the best place to set it?

From code, you can just do self.segmentedControl.selectedSegmentIndex = someDefaultIndex .

Whether you should set it in viewDidLoad: or not depends entirely on the structure of your application. For example, if your app is starting up and loading the view for the first time and needs to set the control to whatever value it had during the previous run of the app, then it definitely makes sense to do it there.

在界面生成器中,当您在 UI 上选择 UISegmentedControl 对象时,然后在属性窗格中,在段控件中有段下拉菜单,选择要选择的段(0,1 等)并勾选其下方的“已选择”选项。

Select default value for your UISegmentedControl via storyBoard

  1. Open ur storyboard and select the UISegmentedControl

在此处输入图片说明

  1. Select atributes inspector of your UISegmentedControl (in the right corner)

在此处输入图片说明

  1. Search the 'segment' atribute and open de dropdown.

在此处输入图片说明

  1. Select the item you want to be selected by default.

在此处输入图片说明

  1. Mark the selected checkbox to set selected by default.

在此处输入图片说明

If you don't use storyboards and want to set a default index after some setup/networking like me, this little snippet will select something if the user hasn't. I placed this in my subclass of UISegmentedControl , but you could place this anywhere. ( Swift 3 )

Decl: var UISegmentedControlNoSegment: Int { get }
Desc: A segment index value indicating that there is no selected segment. See selectedSegmentIndex for further information.

Short version:

if selectedSegmentIndex == UISegmentedControlNoSegment {
    selectedSegmentIndex = initialIndex
}

Longer version

func reloadData() {
    guard let numberOfItems = dataSource?.numberOfItems() else {
        return
    }

    removeAllSegments()

    for index in 0...numberOfItems {
        insertSegment(with: $image, at: index, animated: false)
    }

    if selectedSegmentIndex == UISegmentedControlNoSegment {
        selectedSegmentIndex = initialIndex
    }
}

After clicking the Segmented Control go to where you created the segments and choose the one you want be default. Then below that there will be a Box with "Selected" by it. Select that and it will be default.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM