Swift 中的 UIScrollView 编程方式

UIScrollView Programmatically in Swift

我一直无法找到一种使用 Swift 以编程方式准确启用水平和垂直滚动的方法(我的对象是编程的,因此无法在 IB 中使用自动布局)。

我遵循的教程允许按预期双向滚动。问题是无论您滚动到哪里,我的按钮都停留在占据屏幕一部分的同一位置。我在另一个教程中得到了同样的结果,我很困惑为什么会这样。

我一直没能找到这个问题的答案,所以我假设其他人会觉得这很有用。

这是我的代码。我根据本教程做了一个非常基础的项目:http://koreyhinton.com/blog/uiscrollview-crud.html

class ViewController: UIViewController, UIScrollViewDelegate {
    var scrollView: UIScrollView!
    var containerView = UIView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let buttonOne = UIButton.buttonWithType(UIButtonType.System) as UIButton
        
        buttonOne.frame = CGRectMake(10, 50, 50, 50)
        buttonOne.backgroundColor = UIColor.greenColor()
        buttonOne.setTitle("test", forState: UIControlState.Normal)
        buttonOne.addTarget(self, action: "buttonAction1x1:", forControlEvents: UIControlEvents.TouchUpInside)
        
        self.scrollView = UIScrollView()
        self.scrollView.delegate = self
        self.scrollView.contentSize = CGSizeMake(1000, 1000)
        
        containerView = UIView()
        
        scrollView.addSubview(containerView)
        view.addSubview(scrollView)
        self.view.addSubview(buttonOne)
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        scrollView.frame = view.bounds
        containerView.frame = CGRectMake(0, 0, scrollView.contentSize.width, scrollView.contentSize.height)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

您的代码运行完美,但是在视图上添加 buttonOne 时出现了一个小问题。

您在 self.view 上添加了 buttonOne(即 self.view 的子视图),而不是在 scrollView 上的 containerView。

你应该使用下面的代码

containerView.addSubview(buttonOne)

而不是

self.view.addSubview(buttonOne)

所以你应该使用下面这行

containerView.userInteractionEnabled = true