ios - UIScrollView 无法水平滚动

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

最佳答案

我认为您的问题是在第一个按钮上设置 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)

关于ios - UIScrollView 无法水平滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42673576/

相关文章:

ios - URLSessionDownloadTask 启动时调用的委托(delegate)方法是什么?

swift - Twitter 回调 URL

objective-c - 无限水平滚动 UIScrollView

ios - 有没有办法获取SecKey的 key 类型?

ios - CLLocation didupdatetolocation 未调用

iphone - 核心数据,一对多关系

arrays - 将数组中的可选值赋给 nil

ios - Swift 3,用特殊的lineCap画圆

ios - UIScrollView 不一直向上/向下滚动

ios - setContentOffset 到 scrollView 中的 UIImage loaction