我下面有一个显示红色的“ Hello World!”的代码。在青色视图的中间。单击.cyan颜色和红色“ Hello World!”中的任意位置,将触发警报。
但是,如果我删除了view.backgroundColor = .cyan
代码,则背景现在很暗(黑色)。在黑暗的侧面上敲击不会触发警报。只点击红色的“ Hello World!”将触发警报。
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .cyan
let textLabel = UILabel()
textLabel.text = "Hello World!"
textLabel.textAlignment = .center
view.addSubview(textLabel)
textLabel.backgroundColor = .red
textLabel.snp.makeConstraints {
$0.centerX.equalToSuperview()
$0.centerY.equalToSuperview()
}
view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(showAlert)))
}
为什么会这样呢?如果没有设置.backgroundColor
,视图是否缩小?还是如果未设置.backgroundColor
则无法点击?
更新
根据@ hell0friend的评论,使用以下内容进一步尝试。
使用view.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.0)
,也将使其不可点击。
使用view.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.001)
,使其可点击。
使用view.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.0001)
,将使其不可轻敲。
看起来像alpha值为0.001或更高时,它是可轻敲的,但是当它低于0.001时,它是不可轻敲的。
p / s:所有这些仅发生在ViewController的rootView上,而不发生在子视图上(例如textLabel
)。对于textLabel
,如果我们在其上方设置手势,则无论其alpha级别如何,只要它具有textLabel.isUserInteractionEnabled = true
,它就始终可以轻按。
其他信息
我使用Xcode 11.3.1。我尝试了iOS Target Development 13.2和11.0。它们的行为相同。
尝试使用
view.backgroundcolor = .clear
也许会帮助您,或者只显示整个代码
[很有可能,背景颜色不是黑色,而是清晰的。清除颜色的Alpha值等于零,这就是为什么点击不会触发警报的原因。https://developer.apple.com/documentation/uikit/uicolor/1621945-clearcolor
编辑:要以视觉方式隐藏视图,可以将其hidden属性设置为YES或将其alpha属性更改为0.0。隐藏视图不会从系统接收触摸事件。参见What is the impact of view.alpha = 0 vs view.hidden = YES?