我正在开发一个项目,它在 headerview 上有 UITableView
和 UISwitch
。以下是我的标题 View 代码。我尝试了有关 headerview 上的按钮单击事件的不同问题,但似乎没有一个解决方案有效。
如果有帮助,我正在设置 UITableView
标题高度。
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 100;
}
这是我的标题代码。
class NotificationSettingsTableHeaderView : UIView, ViewProtocol {
//other controls
var mainSwitch : UISwitch!
var contentView : UIView!
weak var temp: SettingCellDelegate?
func handle(sender: UISwitch) {
// ----------- THIS METHOD IS NOT GETTING CALLED ------------
if(sender.isOn){
print("IS ON")
}
else{
print("IS OFF")
}
}
override init(frame: CGRect) {
super.init(frame: frame)
addSubviews()
makeConstraints()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func addSubviews() {
contentView = UIView()
// Other control initialization
mainSwitch = UISwitch()
mainSwitch.addTarget(self, action: #selector(NotificationSettingsTableHeaderView.handle(sender:)), for: UIControlEvents.valueChanged)
contentView.addSubview(mainSwitch)
}
func makeConstraints() {
let screen = UIScreen.main.bounds
contentView.frame = CGRect(x: 0, y: 0, width: screen.width, height: 80)
mainSwitch.snp.makeConstraints { (make) in
make.centerY.equalTo(contentView)
make.right.equalTo(contentView).offset(-10)
}
// other code
}
}
已编辑
我正在使用以下代码将内容 View 添加到 header 。
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView {
let cell = NotificationSettingsTableHeaderView()
let cat = preferenceSection.allSections[section]
cell.label.text = cat.getTitle()
cell.descLabel.text = cat.getSubtitle()
return cell.contentView
}
最佳答案
检查您的 UISwitch 是否在您的 UIView
层次结构中,正如@DonMag 所说,您似乎忘记了将 contentView 添加到 View 层次结构,您的 handle 方法是一个实例方法,不要类方法,所以
在您的addSubviews
方法中更改这一行
mainSwitch.addTarget(self, action: #selector(NotificationSettingsTableHeaderView.handle(sender:)), for: UIControlEvents.valueChanged)
由这个
mainSwitch.addTarget(self, action: #selector(self.handle(sender:)), for: UIControlEvents.valueChanged)
已更新 1
您需要返回您的 NotificationSettingsTableHeaderView
对象,而您返回的是 contentView
在 UITableViewDelegate
的 viewForHeaderInSection
方法中更改这一行
return cell.contentView
这个
return cell
已更新 2
func addSubviews() {
contentView = UIView()
// Other control initialization
mainSwitch = UISwitch()
mainSwitch.addTarget(self, action: #selector(NotificationSettingsTableHeaderView.handle(sender:)), for: UIControlEvents.valueChanged)
self.addSubview(mainSwitch)
}
func makeConstraints() {
mainSwitch.snp.makeConstraints { (make) in
make.centerY.equalTo(self)
make.right.equalTo(self).offset(-10)
}
// other code
}
关于ios - UITableView 的 headerview 中的 UISwitch 正在更改状态但不调用事件处理方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45883086/