我有一个 UIButton,我希望它能够用 pan 手势
移动,但不能单击它。我想要的是当用户点击按钮时按钮不会改变其外观,就像您只是点击一个 View 一样。将 isEnabled
设置为 false
并将 userInteractionIsEnabled
设置为 false
都会导致按钮未接收到平移事件
。我可以通过自定义 View 实现所需的效果,但我可以通过按钮以某种方式实现吗?
根据要求发布带有按钮创建的代码片段:
func createAnswerButton() {
let width : CGFloat = 154
let height : CGFloat = 60
let originX = (view.frame.size.width - width) / 2
let originY = startOverButton.frame.origin.y + collectionView.frame.size.height
let frame = CGRect(x: originX, y: originY, width: width, height: height)
let button = UIButton(frame: frame)
answerButton = button
button.backgroundColor = .clear
self.answerButton.setTitleColor(.white, for: .normal)
let image = UIImage(named: "item_neutral")
button.setBackgroundImage(image, for: .normal)
view.addSubview(button)
let panGesture = UIPanGestureRecognizer(target: self, action: (#selector(MoviesViewController.didPanButton(_:))))
button.addGestureRecognizer(panGesture)
}
最佳答案
要实现此目的,您必须将按钮的 adjustsImageWhenHighlighted
设置为 false
(如果您想以编程方式执行此操作)。在界面生成器中,您可以将按钮 type
更改为 custom
。
以下是以编程方式执行此操作的代码:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let width : CGFloat = 154
let height : CGFloat = 60
let originX = (view.frame.size.width - width) / 2
let originY = (view.frame.size.height - width) / 2
let frame = CGRect(x: originX, y: originY, width: width, height: height)
let button = UIButton(type: .custom)
button.adjustsImageWhenHighlighted = false
button.frame = frame
button.addTarget(self, action: #selector(buttonInCodeTapped), for: .touchUpInside)
button.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(panForButtonInCode(recognizer:))))
button.setBackgroundImage(UIImage(named: "X"), for: .normal)
view.addSubview(button)
}
下面是该属性设置为 true
时的结果(您可以看到,点击时 X
会突出显示):
关于ios - UIButton 不可点击但可接收手势,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49652869/