如何在Swift 3中使用按钮获取触摸输入并将位置输出到标签?

时间:2018-10-23 11:16:27

标签: ios swift touch

我刚开始玩Swift,所以道歉,如果这是一个愚蠢的问题。 我正在尝试创建一个按钮,以便当用户按下该按钮然后触摸图像内的屏幕时,它将把触摸的位置保存为CGPoint并将标签上的文本更改为坐标。

到目前为止,我已经掌握了以下内容,但是我不确定应该使用什么参数来从按钮的touchesBegan调用IBAction函数,或者我是否打算完全这么做。关于这个错误的方式。 任何帮助将不胜感激。

class FirstViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    // *********** Set Coordinates ****************
    // variable to be set as the location of the user's touch
    var toploc:CGPoint? = nil

    @IBOutlet weak var myImageView: UIImageView!

    // label that will change to the coordinates of the touch
    @IBOutlet weak var Topcoord: UILabel!

    func touchesBegan(_ touches:Set<UITouch>, with event: UIEvent?) -> CGPoint {
        if let touch = touches.first {
            let position = touch.location(in: myImageView)
            return position
        } else {
            // print("in else")
        }
    }

    // button that stores location of user's touch and displays the coordinates in the Topcoord text

    @IBAction func settop(_ sender: Any) {
        toploc = touchesBegan(Set<UITouch>, UIEvent)
        Topcoord.text = String(describing: toploc)
    }

    // ************** default stuff ***************
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

2 个答案:

答案 0 :(得分:0)

您不需要从代码中调用touchesBegan函数,因为UIKit调用了此方法。触发此方法后,只需将最后一个位置保存在toploc变量中,然后在用户按下按钮时在settop函数中使用它。例如

var toploc: CGPoint?

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first

    if let position = touch?.location(in: myImageView) {
        toploc = position  // 
    }
}

@IBAction func settop(_ sender: Any)
{
    topCoord.text = String(describing: toploc)
}

Сamel样式在Swift中通常用于名称,对于类型(和协议),首字母大写,对于其他所有内容,小写。因此,如果Topcoord变量名将更改为'topCoord'或'topCoordinates',您的代码将看起来更好。

答案 1 :(得分:0)

您想要的是使用UITapGestureRecognizer,它实际上将为您提供触摸的位置。您可以在情节提要/ XIB中或通过编程将其添加到图像视图中。例如

override func viewDidLoad() {
    super.viewDidLoad()

    let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(viewTapped(_:)))
    myImageView.addGestureRecognizer(tapGestureRecognizer)
}

@IBAction func viewTapped(_ sender: UITapGestureRecognizer) {
    switch sender.state {
    case .ended:
        Topcoord.text = "\(sender.location(ofTouch: 0, in: view))"
    case .possible, .began, .changed, .cancelled, .failed:
        break
    }
}

P.S。您永远不会创建UITouch对象,它们是在UIKit内部私下创建的。