如何通过点击来更改以编程方式添加的图像视图的位置? (图像视图未手动添加到Main.storyboard)

时间:2018-11-08 05:13:24

标签: ios swift

以下是仅用于以编程方式添加图像视图的代码:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let imageName = "thisIsAnImage.png"
        let image = UIImage(named: imageName)
        let imageView = UIImageView(image: image!)
        view.addSubview(imageView)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        // change position of image
    }

}

这就是我现在如何以编程方式添加图像视图的方式。

我可以通过在viewDidLoad函数中编写代码来更改位置,但是此函数仅在运行应用程序开始时运行。

如何在viewDidLoad功能之外编写代码(即用于添加图像视图),以便访问图像并通过点击来更改位置?

2 个答案:

答案 0 :(得分:1)

您应该存储对创建的图像视图的引用,以便可以在touches例程中移动它。示例:

class ViewController: UIViewController {

var imageView : UIImageView!
override func viewDidLoad() {
    super.viewDidLoad()
    let imageName = "image.png"
    let image = UIImage(named: imageName)
    imageView = UIImageView(image: image!)
    view.addSubview(imageView)

    imageView.frame.origin = CGPoint(x: 100, y: 100)
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touchpt = touches.first?.location(in: self.view) {
        imageView.frame.origin = touchpt
    }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touchpt = touches.first?.location(in: self.view) {
        imageView.frame.origin = touchpt
    }

}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touchpt = touches.first?.location(in: self.view) {
        imageView.frame.origin = touchpt
    }

}

}

答案 1 :(得分:0)

您应该使图像视图成为类级别的变量,如下所示:

/index.html -> /home/stuff/stuff/index.html
/images/image1.png -> /home/stuff/stuff/image1.png
/tmp/ -> /home/stuff/stuff/tmp/