enable user interaction by changing alpha swift iOS

混江龙づ霸主 提交于 2020-01-11 12:58:14

问题


I have a view with the tap function (user interaction is enabled). If I set it without changing alpha it works well. But if I try to change alpha of this view with delay, it cannot be tapped during this animation. Could somebody help?

Here is my code:

import UIKit

class ViewController: UIViewController {

var myView = UIView()
var n = 0

override func viewDidLoad() {
    super.viewDidLoad()

    setView()
    changeAlpha()

}

func changeAlpha() {

        UIView.animate(withDuration: 5) {
            self.myView.alpha = 0.1
        }
    }

func setView() {

    let size = view.frame.width
    myView = UIView(frame: CGRect(x: 0, y: 0, width: size/3, height: size/3))
    myView.center = view.center
    myView.backgroundColor = UIColor.red
    view.addSubview(myView)

    myView.isUserInteractionEnabled = true
    let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(gameObjectTapped(_:)))
    myView.addGestureRecognizer(tapGestureRecognizer)

}

@objc func gameObjectTapped(_ recognizer:UITapGestureRecognizer) {

    print("# tap \(n)")
    n+=1

}

回答1:


Run the animation with option .allowUserInteraction:

UIView.animate(withDuration: 5, delay: 0, options: [.allowUserInteraction], animations: {
    self.myView.alpha = 0.1
}, completion: nil)



回答2:


change your

UIView.animate(withDuration: 5) {
    self.myView.alpha = 0.1
}

to

UIView.animate(withDuration: 5, delay: 0.0, options: .allowUserInteraction, animations: {
    self.myView.alpha = 0.1
}, completion: nil)


来源:https://stackoverflow.com/questions/48559553/enable-user-interaction-by-changing-alpha-swift-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!