Swift中UIButton设置isHidden为true后无法隐藏的问题
可能原因及对应方案
1. 重复创建按钮导致旧实例残留
如果这段创建按钮的代码被多次执行,每次都会生成新的UIButton并添加到视图上。哪怕新按钮设置了isHidden = true,之前创建的旧按钮没被移除或隐藏,就会一直显示在界面上——你看到的其实是旧按钮,不是新创建的那个。
解决办法:
创建新按钮前先移除旧实例:
DispatchQueue.main.async { // 先清理旧按钮 self.connect_dropbox_UIButton?.removeFromSuperview() // 再创建新按钮 self.connect_dropbox_UIButton = UIButton(frame: CGRect(x: tap_button_2nd_x, y: tap_row_y, width: tap_buttom_width, height: tap_height )) // 后续的标题、事件、背景色等设置不变 self.connect_dropbox_UIButton.setTitle( "DX", for: .normal ) self.connect_dropbox_UIButton.addTarget( self, action: #selector( self.connect_dropbox ), for: .touchUpInside) self.connect_dropbox_UIButton.backgroundColor = UIColorFromRGB( rgbValue: 0x0080ff ) self.connect_dropbox_UIButton.isHidden = self.is_dropbox_connection(true) self.connect_dropbox_UIButton.isEnabled = true self.view.addSubview(self.connect_dropbox_UIButton) }
或者优化逻辑,只在按钮不存在时才创建,否则直接更新状态:
DispatchQueue.main.async { if self.connect_dropbox_UIButton == nil { self.connect_dropbox_UIButton = UIButton(frame: CGRect(x: tap_button_2nd_x, y: tap_row_y, width: tap_buttom_width, height: tap_height )) self.connect_dropbox_UIButton.setTitle( "DX", for: .normal ) self.connect_dropbox_UIButton.addTarget( self, action: #selector( self.connect_dropbox ), for: .touchUpInside) self.connect_dropbox_UIButton.backgroundColor = UIColorFromRGB( rgbValue: 0x0080ff ) self.connect_dropbox_UIButton.isEnabled = true self.view.addSubview(self.connect_dropbox_UIButton) } // 直接更新隐藏状态即可 self.connect_dropbox_UIButton.isHidden = self.is_dropbox_connection(true) print("show_DX_tap: is_dropbox_connection", self.is_dropbox_connection() ) print("show_DX_tap: connect_dropbox_UIButton.isHidden", self.connect_dropbox_UIButton.isHidden ) }
2. UI状态未及时刷新
虽然代码在主队列执行,但偶尔会因为视图布局的延迟,导致isHidden的状态没立刻同步到界面。可以强制触发视图刷新:
解决办法:
设置isHidden后调用刷新方法:
connect_dropbox_UIButton.isHidden = is_dropbox_connection(true) // 强制按钮刷新显示状态 connect_dropbox_UIButton.setNeedsDisplay() // 或者刷新父视图布局 self.view.layoutIfNeeded()
3. 其他代码意外修改了isHidden状态
检查按钮点击事件connect_dropbox方法,或者其他业务逻辑代码里,有没有不小心把isHidden又设回false的情况。比如:
@objc func connect_dropbox() { // 确认这里的设置是正确的 connect_dropbox_UIButton.isHidden = true // 打印状态确认 print("点击后isHidden状态:", connect_dropbox_UIButton.isHidden) }
4. 视图层级异常
可以打印视图层级确认是否有重复按钮,或者按钮的父视图有特殊设置:
print("按钮父视图:", connect_dropbox_UIButton.superview) print("当前视图所有子视图:", self.view.subviews)
通过输出可以确认界面上的按钮是不是你设置了isHidden的那个实例,有没有其他重复的按钮存在。
内容的提问来源于stack exchange,提问作者Doug Null
相关产品推荐
相关产品推荐

