UIScrollView无法水平滚动

时间:2017-03-08 14:10:52

标签: ios swift uiscrollview

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

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时,我可以拖动滚动视图并查看其他按钮,但它会反弹回原始状态。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:1)

更改此

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

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

答案 1 :(得分: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)

答案 2 :(得分:0)

Rajeshkumar R给你的答案,或更好地使用约束。您可以在myScrollView左侧和左侧第一个按钮(&#34;前导空格&#34;约束)之间设置约束,然后在每个按钮和前一个按钮之间设置前导空格约束,当您完成循环,从最后一个按钮到myScrollView的尾随空格。

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