如何让按钮在 Swift 中随背景滚动?

How to have buttons scroll with background in Swift?

我有一张图片,您可以使用 UIScrollView 滚动浏览。我想给它添加按钮。按钮需要与图像保持连接并随图像滚动,而不是单独移动。我需要这一切以编程方式完成。

这是我现在拥有的代码:

imageView = UIImageView(image: UIImage(named: "Map 1.png"))

// 2
scrollView = UIScrollView(frame: view.bounds)
scrollView.backgroundColor = UIColor.blackColor()
// 3
scrollView.contentSize = imageView.bounds.size
// 4
scrollView.addSubview(imageView)
view.addSubview(scrollView)

scrollView.contentSize.height = scrollView.frame.size.height

您只需要将按钮添加到滚动视图:

var button   = UIButton.buttonWithType(UIButtonType.System) as UIButton
button.frame = CGRectMake(100, 100, 100, 50)
button.backgroundColor = UIColor.greenColor()
button.setTitle("Button", forState: UIControlState.Normal)
button.addTarget(self, action: "Action:", forControlEvents: UIControlEvents.TouchUpInside)
scrollView.addSubview(button)