ios - 如果以编程方式添加,UISwitch 不会响应操作
问题描述
无法解决此问题。有这个功能:
func addSwitch(){
switchB.setOn(true, animated: false)
switchB.addTarget(self, action: #selector(valueChange), for:UIControl.Event.valueChanged)
view.addSubview(switchB)
switchB.translatesAutoresizingMaskIntoConstraints = false
switchB.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
switchB.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -16).isActive = true
}
@objc func valueChange(mySwitch: UISwitch) {
if mySwitch.isOn{
switchB.onTintColor = UIColor.black
}
else{
switchB.onTintColor = UIColor.white
}
}
然后我将其添加到viewDidLoad()
:
override func viewDidLoad() {
super.viewDidLoad()
addSwitch()
}
我看到了按钮,但它不响应操作。
升级版:
class Main: UIViewController, UIGestureRecognizerDelegate, UITableViewDelegate, UITableViewDataSource,CLLocationManagerDelegate {
let switchB = UISwitch()
override func viewDidLoad() {
super.viewDidLoad()
addSwitch()
}
一切都在新项目中有效,但在当前 - 不。我使用谷歌地图,也许地图层有问题,但我看到了我的按钮。
UPD2:工作!(感谢 Francesco Deliro)google mapView 设置属性有一个名为 consumesGestureInView 的属性,默认设置为 true 尝试:yourMapView.settings.consumesGestureInView = false
解决方案
您的代码没有问题。色调颜色动作正在发挥作用。确保 switchbB 变量是正确的。
var switchbB = UISwitch()
func addSwitch(){
switchbB.setOn(true, animated: false)
switchbB.addTarget(self, action: #selector(valueChange), for:UIControl.Event.valueChanged)
view.addSubview(switchbB)
switchbB.translatesAutoresizingMaskIntoConstraints = false
switchbB.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
switchbB.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -16).isActive = true
}
@objc func valueChange(mySwitch: UISwitch) {
if mySwitch.isOn{
switchbB.onTintColor = UIColor.black
}
else{
switchbB.onTintColor = UIColor.white
}
}
推荐阅读
- reactjs - 使 React 应用程序路由服务于静态文件夹
- ios - 如何使用 iOS 应用程序运行 Appium
- java - 如何使用 iText 列表将具有不同权重的文本添加到单个 ListItem
- python-3.x - 根据由空格分隔的字符长度删除值
- r - lapply 循环根据经过的时间跳到下一次迭代
- python - SQLAlchemy 从 Table 对象(从 Metadata 或 Session 或其他)获取 Mapper 对象
- html - 在 Angular 7 中,下拉菜单的默认选择值并不直接
- r - R read.xlsx 注释字符选项
- scala - Websocket 客户端不接收来自 Akka 流 Source.queue 的数据
- python - 出现错误 python setup.py build_ext --inplace VC C++ 14.0 required