use*_*092 23 iphone uiscrollview ios swift
我一直无法找到一种使用Swift以编程方式准确启用水平和垂直滚动的方法(我的对象是程序化的,因此在IB中使用自动布局是不可行的).
我遵循的教程允许按预期滚动两种方式.问题是无论你在哪里滚动,我的按钮都会停留在占据屏幕一部分的同一位置.我在另一个教程中得到了相同的结果,我很困惑为什么会发生这种情况.
我无法找到答案,所以我假设其他人会发现这有益.
这是我的代码.我根据本教程制作了一个非常基础的项目:http://koreyhinton.com/blog/uiscrollview-crud.html
import UIKit
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(即self.view的子视图)上添加了buttonOne,而不是在scrollView上的containerView.
您应该使用以下代码
containerView.addSubview(buttonOne)
代替
self.view.addSubview(buttonOne)
| 归档时间: | 
 | 
| 查看次数: | 38643 次 | 
| 最近记录: |