当 alpha 为 0 时,按钮不会触发操作

Button doesn't trigger action when the alpha is 0

我有一个按钮,当他的 alpha 为 1 时工作正常,但是当我将 alpha 设置为 0 时,它不执行这些功能。 (我希望按钮不可见,但仍然有响应)。 我该如何解决?

谢谢!

将alpha设置为0,将禁用UIView并且不会接收到触摸事件,因此您至少需要将其设置为0.02。

来源是 SO 上的这个答案:当 UIButton 的 alpha 设置为 0.0 时,它会被禁用吗?

根据Apple Docs

This method ignores view objects that are hidden, that have disabled user interactions, or have an alpha level less than 0.01. This method does not take the view’s content into account when determining a hit. Thus, a view can still be returned even if the specified point is in a transparent portion of that view’s content.

任何 alpha 低于 0.01 的 UIView 都将被触摸事件处理系统忽略,即不会接收到触摸。 至少设置 0.02

UIButton 的 alpha 设置为零将不允许从中获取任何触摸事件。

相反,您可以保留 alpha 1.0 并将背景颜色设置为 UIColor.clear,并将文本设置为 ""(空)。这样,按钮就会像您要求的那样不可见,但仍然可以点击。

您可以在按钮上方添加另一个视图并使其颜色清晰,以便它与您的背景颜色相同,并使用 alpha 0 轻松隐藏您的按钮并向您在上方添加的视图添加点击手势按钮,以便当您点击视图时它会执行一个操作

let tap = UITapGestureRecognizer(target: self, action:#selector(self.handleTap(_:)))

aboveButtonView.addGestureRecognizer(tap)

aboveButtonView.isUserInteractionEnabled = true

self.view.addSubview(aboveButtonView)

// function which is triggered when handleTap is called
@objc func handleTap(_ sender: UITapGestureRecognizer) {
   // do action needed
}