简体   繁体   中英

Removing the shadow on a UIButton while it's being held

I have a UIButton which highlighted state involves removing the shadow. What I tried doing is putting a UILongPressGestureRecognizer onto the button:

let gesture = UILongPressGestureRecognizer(target: self, action: #selector(self.removeShadow))
gesture.numberOfTapsRequired = 1
gesture.numberOfTouchesRequired = 1
gesture.delaysTouchesBegan = false
gesture.delaysTouchesEnded = false
gesture.minimumPressDuration = 0.01
self.addGestureRecognizer(gesture)

Then in my action, I'm using the states to hide and show the shadow:

 @objc func removeShadow(gesture: UILongPressGestureRecognizer) {
    if gesture.state == .recognized {
        UIView.animate(withDuration: 0.1, animations: {
            self.layer.shadowOpacity = 0
        })
    } else if gesture.state == .ended {
        UIView.animate(withDuration: 0.1, animations: {
            self.layer.shadowOpacity = 0.15
        })
    }
}

However, this doesn't seem to trigger anything. The shadow keeps living under the button. Am I missing something here?

Thanks.

Your gesture recognizer is being overridden by the selector of the button. It'd be better in your scenario to override the button and hide its shadow when it's selected.

class ShadowButton: UIButton {
    override var isHighlighted: Bool {
        didSet {
            UIView.animate(withDuration: 0.1) {
                self.layer.shadowOpacity = self.isHighlighted ? 0 : 0.15
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM