【发布时间】:2017-02-22 14:57:36
【问题描述】:
我第一次尝试在 Swift 中完全以编程方式制作应用程序,但在使用 UITableViews 时遇到了问题。 我创建了一个自定义的可重用单元格,我称之为“exerciseCell”,其中有一个 UILabel、一个 UIImageview 和一个 UISwitch。
我的问题是,当我选择第 0 行上的开关时,它也会打开第 3 行和第 6 行上的开关。这对于每个单元格都是一样的,它们分别影响大约三个单元格。 此表格视图的目的是能够选择您想要的练习列表中的哪些练习,但每个练习都需要能够独立选择。
这是单元格的代码:
class exerciseCell: UITableViewCell {
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")
}
var cellSelected:Bool = false
let excersiseLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.textColor = UIColor.red
label.textAlignment = NSTextAlignment.center
return label
}()
let excersiseImage: UIImageView = {
let image = UIImageView()
image.backgroundColor = UIColor.blue
image.translatesAutoresizingMaskIntoConstraints = false
return image
}()
let thisSwitch: UISwitch = {
let thisSwitch = UISwitch()
thisSwitch.isOn = false
thisSwitch.translatesAutoresizingMaskIntoConstraints = false
return thisSwitch
}()
func setupViews() {
addSubview(excersiseLabel)
addSubview(excersiseImage)
addSubview(thisSwitch)
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[v0]|", options: NSLayoutFormatOptions.alignAllCenterX, metrics: nil, views: ["v0": excersiseLabel]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-101-[v0(100)]-101-|", options: .alignAllCenterX, metrics: nil, views: ["v0": excersiseImage]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-120-[v0(100)]-120-|", options: NSLayoutFormatOptions.alignAllCenterX, metrics: nil, views: ["v0": thisSwitch]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-12-[v0(30)]-8-[v1(100)]-12-[v2(30)]-12-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": excersiseLabel, "v1": excersiseImage, "v2": thisSwitch]))
}
}
还有cellForRow如下:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var thisCell = UITableViewCell()
if tableView == self.tableView {
let aCell = tableView.dequeueReusableCell(withIdentifier: "thirdCellID", for: indexPath) as! exerciseCell
aCell.excersiseLabel.text = "\(mobility[indexPath.row])"
aCell.thisSwitch.tag = indexPath.row
thisCell = aCell
}
return thisCell
}
如何让单元格独立响应用户?如果需要澄清,我可以提供更多代码。
【问题讨论】:
标签: ios swift uitableview uiswitch