UISegmentedControl.noSegment stopped working with Xcode 11, iOS 13 [duplicate]

旧街凉风 提交于 2019-12-05 20:37:43

Thanks for asking this question. I ran into the same issue, so was great to get some confirmation it wasn't just something I was missing.

While Apple hopefully fixes this bug soon, I implemented the following workaround by recreating the segments. This code sample is based on a UISegmentedControl with images as segments, you could of course implement the same approach for title strings:

public func resetSegmentedControl(_ control: UISegmentedControl) {
    if #available(iOS 13, *) {
        // workaround: recreate the segments
        let numSegments = control.numberOfSegments
        let segmentImages = (0..<numSegments).compactMap { control.imageForSegment(at: $0) }
        control.removeAllSegments()
        for (index, image) in segmentImages.enumerated() {
            control.insertSegment(with: image, at: index, animated: false)
        }
    } else {
        // for earlier versions of iOS, just reset the selectedSegmentIndex
        control.selectedSegmentIndex = UISegmentedControl.noSegment
    }
}

There's a slight flicker when removing and re-inserting the segments, but for me that's preferable to the broken state.

EDIT

As pointed out by @matt in the comment below, all that's needed is a call to setNeedsLayout,i.e.:

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