2017-03-08 142 views
0

我在UIViewController中有一个UIScrollView,我期望它水平滚动。我通过循环以编程方式将按钮添加到ScrollView。循环之后,我将myScrollView.contentSize.width设置为buttonWidth * numberOfButtons。我也仔细检查,以确保contentSize大于scrollview的框架(在这种情况下,滚动视图的宽度为375)。UIScrollView无法水平滚动

let numberOfButton = 7   
for index in 0..<numberOfButton { 
    let button = UIButton() 
    let frame = CGRect(x: 80 + (index * 80), y: 6, width: 60, height: 32) 
    button.setTitle("Button" + String(index), forState: .Normal) 
    button.frame = frame 
    button.titleLabel?.font = UIFont(name: "Museo Sans", size: 16) 
    button.setTitleColor(UIColor.blueColor(), forState: .Normal) 

    myScrollView.addSubview(button) 
} 
myScrollView.contentSize = CGSize(width: 100*numberOfButtons, height: 42) 

当我运行代码时,它只出现在Button3(有7个按钮),我不能将它滚动到最后。但是,当我设置myScrollView.bounces = true我可以拖动滚动视图并查看其他按钮,但它会弹回原始状态。任何帮助将非常感激。

+0

IMO你应该使用一个collectionview呢?另外,在这之后myScrollView.contentSize的值是多少。你可以打印它看到 – Devster101

+0

myScrollView.frame(0.0,60.0,375.0,42.0)/ myScrollView.contentSize(700.0,42.0) –

+0

内容似乎没问题,我唯一能想到的其他事情可能是启用滚动。添加在myScrollView.isScrollEnabled = true – Devster101

回答

1

更改此

tagBar.contentSize = CGSize(width: 100*7, height: 42) 

myScrollView.contentSize = CGSize(width: 100*7, height: 42) 
+0

其实,这只是一个错字错误。我刚编辑我的代码。问题依旧 –

0

答案是Rajeshkumar [R给你,或者更好的使用限制。您可以在myScrollView的左边和第一个按钮(“前导空间”约束)之间设置一个约束,然后在每个按钮和前一个按钮之间设置一个前导空间约束,并且在完成循环时,将从上一个尾部空间开始按钮到myScrollView

这样你就不必自己计算contentSize。它也更具可扩展性(例如,如果您有不同大小的按钮,则必须知道每个宽度,然后将所有宽度相加,然后使用scrollView ...对元素之间以及第一个和最后一个之间的边距进行求和)。

1

我认为你的问题是在第一个按钮上设置X值。我刚刚试过这段代码,它工作正常

let numberOfButtons = 7 
    for index in 0..<numberOfButtons { 
     let button = UIButton() 
     let frame = CGRect(x: 8 + (index * 96), y: 6, width: 80, height: 32) 
     button.setTitle("Button \(index)", for: .normal) 
     button.frame = frame 
     button.titleLabel?.font = UIFont(name: "Museo Sans", size: 16) 
     button.setTitleColor(UIColor.blue, for: .normal) 

     myScrollView.addSubview(button) 
    } 
    myScrollView.contentSize = CGSize(width: 100*numberOfButton, height: 42) 
+0

我已经解决了这个问题。发生这种情况是因为我在XIB中有一个默认按钮(只是第一个,其他人是动态创建的),并且它具有父视图的约束,这就是为什么我无法从第一个按钮中滚出。我已阅读您的评论和解决方案。尽管他们没有回答这个问题,但他们给我提供了解决这个问题的线索。非常感谢你。 –

+0

啊,我会尽量避免同时拥有静态和动态视图。它可能会变得非常混乱。 – Devster101