ios - UIScrollView 中 UIImageView 的对齐

标签 ios swift uiscrollview uiimageview

我在很多地方都看到过这个主题,但我不明白为什么我的代码不起作用。

我有一张从 -90 度到 90 度的人造地平线图像。我想通过一个只显示大约 -20 到 20 度的小窗口查看它。然后我想根据我的机器人倾斜的角度上下移动图像。

我首先将 UIImage 添加到 UIImageView。所有对齐都是正确的。然后我认为上下移动图像的最简单方法是将 UIImageView 添加到 UIScrollView。现在我不知道如何正确对齐。如果我在 ScrollView 中拖动,我会在其中看到图像,但一旦我放手,它就会回到原来的位置。

这是我的代码。这是我写的第一个 Swift 代码,所以如果有更好的方法来做到这一点,我欢迎任何 mock (开玩笑,温柔一点)

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

关于ios - UIScrollView 中 UIImageView 的对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39069555/

相关文章:

iphone - 如何使用来自 iPhone 应用程序的 FBConnect 在我的 feed-post 中包含一个链接?

ios - 更改 StatusBar 背景颜色和 preferredStatusBarStyle 的最佳方法应该是什么?

iOS 11 大导航栏标题出乎意料的速度

iphone - 从 UIView 子类访问 UINavigationController

ios - 如何在 Interface Builder 中使用 UIScrollView?

ios - 不同 viewController 通用的 UIScrollView

ios - Sprite Kit 停止脉冲

ios - 来自 iOS 的 Firebase 云消息传递和多主题订阅失败

ios - 是否可以用视频设置 GIF 图像?

json - 使用 Codable 协议(protocol)从 JSON API 解码包含的部分