ios UIScrollView 在 Swift 中以编程方式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28848852/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
UIScrollView Programmatically in Swift
提问by user3246092
I've been unable to find a way of accurately enabling horizontal and vertical scrolling programmatically with Swift (my objects are programmatic thus making using auto layout in IB unfeasible).
我一直无法找到一种使用 Swift 以编程方式准确启用水平和垂直滚动的方法(我的对象是编程的,因此在 IB 中使用自动布局是不可行的)。
The tutorial I followed allows for scrolling both ways as intended. The problem is my button stays in the same spot occupying part of the screen no matter where you scroll. I've had this same result with another tutorial and am quite confused as to why this is happening.
我遵循的教程允许按预期方式滚动。问题是无论您滚动到哪里,我的按钮都停留在占据屏幕部分的同一位置。我在另一个教程中得到了同样的结果,并且很困惑为什么会发生这种情况。
I haven't been able to find an answer to this so I'm assuming some others will find this beneficial.
我一直无法找到答案,所以我假设其他一些人会发现这很有用。
Here is the code I have. I made a very basic project based on this tutorial: http://koreyhinton.com/blog/uiscrollview-crud.html
这是我的代码。我根据本教程制作了一个非常基本的项目: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()
}
}
采纳答案by Pankaj purohit
Your code is working perfectly, but there is a small problem in adding buttonOne on the view.
您的代码运行良好,但在视图上添加 buttonOne 时存在一个小问题。
You have added buttonOne on self.view (i.e subview of self.view), not containerView which is on scrollView.
您在 self.view(即 self.view 的子视图)上添加了 buttonOne,而不是在 scrollView 上的 containerView。
You should use the following code
您应该使用以下代码
containerView.addSubview(buttonOne)
instead of
代替
self.view.addSubview(buttonOne)
回答by Samrez Ikram
So you should use following line
所以你应该使用以下行
containerView.userInteractionEnabled = true