ios - 在 Swift 中使用 touchesBegan

标签 ios swift

我在使用函数 touchesBegan 时遇到了一些问题。问题是当 touchesBegan 执行时,图像人物跳到 Main.storyboard 开头定义的位置。这是我的代码:

    var location = CGPoint(x: 0, y: 0)


    @IBOutlet weak var person: UIImageView!

    @IBOutlet weak var value: UILabel!




    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
        let touch: UITouch = touches.first as! UITouch

        location = touch.locationInView(self.view)
        person.center = location

        value.text = "X: \(person.center.x), Y: \(person.center.y)"
    }

    override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
        var touch: UITouch = touches.first as! UITouch

        location = touch.locationInView(self.view)
        person.center = location

当我添加行时出现问题:

value.text = "X: \(person.center.x), Y: \(person.center.y)"

知道为什么吗?我打印了location和person.center,它们都指向我点击的位置。但是 image person 会转到程序开始时定义的位置。

最佳答案

您需要告诉 ImageView 重绘自身:

person.setNeedsDisplay()

或者您可以将内容模式设置为在 ImageView 边界更改时重新绘制自身:

person.contentMode = UIViewContentModeRedraw // Only once

关于ios - 在 Swift 中使用 touchesBegan,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30012729/

相关文章:

ios - 具有深色效果的圆形 UIButton

ios - 从 subview 启动时 ImagePickerController 立即被解雇

ios - 仅当隐藏文本字段时才使用键盘移动 View

objective-c - 在 Objective-C++ 代码中的 C++ 代码中编译 C 代码

ios - CoreData "keypath not found "错误未说明缺少的关键路径

iphone - 在 iOS 下,有没有办法确定崩溃报告中正在执行的架构?

ios - 我如何在我的应用程序中通过播放器播放 UNNotificationSound.default()?

iOS AWS S3/DynamoDB 云存储视频录制应用设计

ios - SwiftUI 中 UISplitViewController 的等价物是什么

xcode - 用于 Swift 框架文档的 XCODE IDE 中的上下文相关帮助