Scroll dynamic UISegmentedControl in Swift 3

允我心安 提交于 2019-12-04 14:06:20

It's better to use another controller rather then segment controller to achieve your goal.

But If you are going with segment controller only then you must add segment controller to scroll view, because titles are dynamic so we can't recognise hows it's wide that's why.

First add segment controller to scroll view. and segment controller has method name setWidth(_ width: CGFloat, forSegmentAt segment: Int) to set width of each segment at index.

so here I'm writing my logic .

    var scrollViewWidth:Float = 0.0
    let items  = ["All Fruits", "Orange", "Grapes", "Banana",  "Mango", "papaya", "coconut", "django"]
    for (index, element) in items.enumerated() {
        let size = element.size(attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 20.0)]) //you can change font as you want
        segmentCon.setWidth(size.width, forSegmentAt: index)
        scrollViewWidth = scrollViewWidth + Float(size.width)
    }

    // Here you can set content width of UIScollView by use of "scrollViewWidth"
    // scrollView.contentSize = CGSize(width: scrollViewWidth, height: 40)// height should whatever you want.

You can try like

[[UILabel appearanceWhenContainedIn:[UISegmentedControl class], nil] setNumberOfLines:0];

segment.apportionsSegmentWidthsByContent = YES;

Swift :

Something like,

   UILabel.appearance(whenContainedInInstancesOf: [UISegmentedControl.self]).numberOfLines = 0
   segment.apportionsSegmentWidthsByContent = true

and you can take your segmented control in scrollview. But with UISegmentedControl you should not use more than four or five segment. It's main purpose is to show three or four options! You should try different mechanism to achieve your goal!

You should refer this post also if it can help!

Try this https://github.com/lestadNew/SASScrolletSegment, I don't find solution and write own cocoa pods

Hope this help you

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