在Swift 3中滚动动态UISegmentedControl [英] Scroll dynamic UISegmentedControl in Swift 3

查看:69
本文介绍了在Swift 3中滚动动态UISegmentedControl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个包含20多个项目的动态UISegmented视图.我试过了,但是输出是这样的.

Hi i want to create a dynamic UISegmented View with more than 20 Items. I tried it, but the output is like this.

切成薄片的文本无法完全看到.我希望它向左和向右滚动并显示全文.有人可以帮我解决这个问题吗?tnx

the text is sliced not visible fully. I want it to scroll to the left and right and also display the full text. can some one help me to fix this. tnx

视图控制器

override func viewDidLoad() {
    super.viewDidLoad()

    let items = ["All Fruits", "Orange", "Grapes", "Banana",  "Mango", "papaya", "coconut", "django"]
    let filtersSegment = UISegmentedControl(items: items)
    filtersSegment.frame = CGRect.init(x: 10, y: 60, width: 300, height: 50)
    filtersSegment.selectedSegmentIndex = 0
    filtersSegment.tintColor = UIColor.black
    filtersSegment.addTarget(self, action: #selector(self.filterApply), for: UIControlEvents.valueChanged)
    self.view.addSubview(filtersSegment)
}

@objc private func filterApply(segment:UISegmentedControl) -> Void {
    print("Selected Index : \(segment.selectedSegmentIndex)")
}

推荐答案

最好使用其他控制器,而不要使用分段控制器来实现您的目标.

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.

首先将细分控制器添加到滚动视图.并且段控制器具有方法名称 setWidth(_ width:CGFloat,forSegmentAt segment:Int)来设置索引处每个段的宽度.

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.

这篇关于在Swift 3中滚动动态UISegmentedControl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆