我在LongPressViewController
类中收到以下错误。
import UIKit
class LongPressViewController: UIViewController {
@IBOutlet weak var imgView: UIImageView!
@IBAction func btnTekan(_ sender: UILongPressGestureRecognizer) {
if sender.state == UIGestureRecognizer.State.began {
let alertController = UIAlertController(title: nil, message: "Long Press terdeteksi", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alertController, animated: true)
}
}
override func viewDidLoad() {
super.viewDidLoad()
let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(_:)))
}
@objc func handleLongPress(_ recognizer: UILongPressGestureRecognizer){
switch recognizer.state {
case .began:
UIView.animate(withDuration: 0.05,
animations: {
self.imgView.transform = CGAffineTransform(scaleX: 1.5, y: 1.5)
},
completion: nil)
case .ended:
UIView.animate(withDuration: 0.05) {
self.imgView.transform = CGAffineTransform.identity
}
default:
break
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
答案 0 :(得分:1)
您应该指出在代码的哪一行上报告了什么错误。
照原样,您的代码可能会警告您从未使用在longPressGesture
中声明和初始化的常量viewDidLoad()
。这不是错误,只是友好的提醒,此行无效。您可以通过添加以下行来将识别器附加到受控视图:
view.addGestureRecognizer(longPressGesture)
或者,您可以将longPressGesture
声明为@IBOutlet
并将其附加到Interface Builder中。
进一步使用State
的地方,属性state
隐含了类型UIGestureRecognizer.State
,因此您可以将行缩短为
if sender.state == .began {