[英]Alignment of UIImageView within UIScrollView
我在很多地方都看到了这个主题,但是我无法弄清楚为什么我的代码无法正常工作。
我有一个从-90到90度的人造地平线图像。 我想通过一个小窗口查看它,该窗口仅显示-20至20度。 然后,我想根据机器人倾斜的角度上下移动图像。
我首先将UIImage添加到UIImageView。 所有对齐方式都是正确的。 然后,我认为上下移动图像的最简单方法是将UIImageView添加到UIScrollView。 现在我不知道如何正确对齐。 如果在滚动视图中拖动,我会在其中看到图像,但是一旦松开,它就会回到原来的位置。
这是我的代码。 这是我编写的第一个Swift代码,因此,如果有更好的方法可以做到这一点,我欢迎任何嘲笑(开个玩笑,要谦虚)
override func viewDidLoad() {
super.viewDidLoad()
let imageRect = CGRectMake(self.view.frame.width / 2 - 100, self.view.frame.height / 2, 200, 200)
self.myImageView = UIImageView.init()
self.myImageView = UIImageView(frame: imageRect)
self.myImageView.contentMode = UIViewContentMode.Center
self.myImageView.clipsToBounds = true
self.myImageView.image = UIImage.init(named:"horizon")
//self.view.addSubview(self.image)
self.myScrollView = UIScrollView(frame: imageRect)
self.myScrollView.contentSize = CGSize(width: imageRect.width, height: imageRect.height)
self.myImageView.center = self.myScrollView.center
self.myScrollView.frame = imageRect
self.myScrollView.backgroundColor = UIColor.blackColor()
self.myScrollView.contentOffset = CGPoint(x: 0, y: 0)
self.myScrollView.addSubview(self.myImageView)
self.view.addSubview(self.myScrollView)
/////////
self.connectionStatusLabel.text = "Disconnected"
self.connectionStatusLabel.textColor = UIColor.redColor()
self.textBox.font = UIFont(name: self.textBox.font!.fontName, size: 8)
// Watch Bluetooth connection
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.connectionChanged(_:)), name: BLEServiceChangedStatusNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.dataReceived(_:)), name: BLEDataChangedStatusNotification, object: nil)
// Start the Bluetooth discovery process
btDiscoverySharedInstance
}
您必须将scrollView的contentSize设置为实际的图像大小,而不是imageView的大小。 并将imageView的大小也设置为实际的图像大小:
let image = UIImage.init(named:"horizon")
// Set the imageView's size to the actual image size
self.myImageView.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
...
...
// Set the scrollView's contentSize to the actual image size
self.myScrollView.contentSize = image.size
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.