【发布时间】:2018-05-25 06:42:44
【问题描述】:
我完全迷路了。我在我的一个屏幕中有一个切换按钮(UISwitch) 我已经向开关添加了一个目标以识别开关中的变化。但是,当切换开关时,什么也没有发生,我感到困惑和迷失。
import Foundation
import UIKit
class PrivateCell: UITableViewCell {
var stackView: UIStackView?
let switchStatementLabel : UILabel = {
let switchStatementLabel = UILabel()
switchStatementLabel.textAlignment = .justified
switchStatementLabel.text = "Make Profile Private"
return switchStatementLabel
}()
let privateSwitch : UISwitch = {
let privateSwitch = UISwitch(frame: CGRect(x: 0, y: 0, width: 70, height: 70))
privateSwitch.isOn = false
privateSwitch.onTintColor = UIColor.rgb(red: 44, green: 152, blue: 229)
privateSwitch.addTarget(self, action: #selector(switchToggled(_:)), for: UIControlEvents.valueChanged)
return privateSwitch
}()
@objc func switchToggled(_ sender: UISwitch) {
if privateSwitch.isOn {
print("switch turned off")
}else{
print("switch turned on")
}
}
@objc func setupViews(){
backgroundColor = .white
stackView = UIStackView(arrangedSubviews: [ switchStatementLabel, privateSwitch])
stackView?.axis = .horizontal
stackView?.distribution = .equalSpacing
// stackView?.spacing = 10.0
if let firstStackView = stackView{
self.addSubview(firstStackView)
firstStackView.snp.makeConstraints { (make) in
make.edges.equalTo(self).inset(10)
}
}
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
我已经添加了我的代码,任何人都可以帮助我
【问题讨论】:
-
看起来当添加目标时单元格尚未初始化,您是否尝试从其他地方调用 setupviews ?
-
只是将其更改为惰性 var 并修复了它