How can I enable multiple segments of a UISegmentedControl to be selected?

后端 未结 6 1575
太阳男子
太阳男子 2021-01-04 06:44

Lets say my UISegmentedControl has 8 numbered segments. I would like for the user to be able to turn on 2, 3, or more of them at once. Toggling them. Essentially like a bits

相关标签:
6条回答
  • 2021-01-04 06:58

    I recommend you try https://github.com/tayhalla/THSegmentedControl
    it is an actual subclass of UISegmentedControl so it fits nicely with Interface builder and everything.

    0 讨论(0)
  • 2021-01-04 07:03

    This isn't possible using UIKit. I would recommend creating a custom control, or an array of UISwitch controls, representing each of the options in your UISegmentedControl.

    0 讨论(0)
  • 2021-01-04 07:08

    There appears to be a way to do this in XCode now. In the Attributes Inspector, there is a section with Segment, Title, Image, Behavior. The behavior options are "Enabled" and "Selected". You can selecte "Selected" for multiple segments.

    0 讨论(0)
  • 2021-01-04 07:08

    Answer for those who will come here from Google: it's now possible to change the behaviour of a UISegmentedControl. Go to Inspector -> Mode -> Select Any instead of Select One. To find out which segments are selected I suggest to create a function like this one:

    extension UISegmentedControl {
        func getBarState() -> [Bool] {
            var states: [Bool] = []
            for i in 0..<segmentCount {
                states.append(isEnabledForSegment(forSegment: i))
            }
            return states
        }
    }
    

    As Google brought me here while searching for the OSX version I'll also post a working solution for NSSegmentedControl:

    extension NSSegmentedControl {
        func getBarState() -> [Bool] {
            var states: [Bool] = []
            for i in 0..<segmentCount {
                states.append(isSelected(forSegment: i))
            }
            return states
        }
    }
    
    0 讨论(0)
  • 2021-01-04 07:09

    I think the simplest way is to create your own segmentedcontrol with UIButton.

    Marco

    0 讨论(0)
  • 2021-01-04 07:16

    This is the best custom control I've found that allows multiple segments to be selected concurrently:

    https://github.com/yonat/MultiSelectSegmentedControl

    This one is a subclass of UISegmentedControl, which is convenient. I've forked it here:

    https://github.com/stewartmacdonald/MultiSelectSegmentedControl

    and added some code examples to the ReadMe and added a method that allows you to get an NSArray of the titles of all selected segments.

    0 讨论(0)
提交回复
热议问题