【问题标题】:UIScrollView Programmatically in SwiftUIScrollView 在 Swift 中以编程方式
【发布时间】:2015-03-04 07:34:16
【问题描述】:

我一直无法找到一种使用 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()
    }
}

【问题讨论】:

  • 尝试将按钮添加到scrollView或containerView

标签: ios iphone swift uiscrollview


【解决方案1】:

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

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

你应该使用下面的代码

containerView.addSubview(buttonOne)

而不是

self.view.addSubview(buttonOne)

【讨论】:

  • 这很有道理,但我从来没有想过。谢谢!
【解决方案2】:

所以你应该使用以下行

containerView.userInteractionEnabled = true

【讨论】:

    猜你喜欢
    • 2018-03-13
    • 2015-05-19
    • 2015-05-19
    • 1970-01-01
    • 1970-01-01
    • 2017-04-03
    • 1970-01-01
    • 2021-10-04
    • 1970-01-01
    相关资源
    最近更新 更多