如何解决如何从TableViewCell单元格激活滑块IBAction?
我的程序正在动态单元格中创建滑块。我不能只在滑块上使用ctrl +“拖放”来创建IBAction,因为它位于单元格中,而不位于viewController中。如何在ViewController中创建此IBAction?
class SecondViewController: UIViewController {
var gradesNumber: Int?
var gradeArray: [Grade] = []
@IBOutlet weak var topLabel: UILabel!
@IBOutlet weak var gradesTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
gradesTableView.dataSource = self
for i in 1...gradesNumber! {
gradeArray.append(Grade(sliderValue: 5,title: "Grade \(i)",grade: "5"))
}
gradesTableView.register(UINib(nibName: "TableViewCell",bundle: nil),forCellReuseIdentifier: "ReusableCell")
}
@IBAction func calculateButton(_ sender: UIButton) {
var avg = 0.0
for i in gradeArray {
avg += Double(i.grade)!
}
topLabel.text = "Avg: \(avg/Double(gradesNumber!))"
}
}
extension SecondViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
return gradesNumber ?? 1
}
func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ReusableCell",for: indexPath) as! TableViewCell
cell.gradeSlider.tag = indexPath.row
cell.gradeSlider.setValue(5,animated: true)
let slider: Grade = gradeArray[indexPath.row]
cell.gradeValue.text = slider.grade
cell.gradeNumber.text = slider.title
return cell
}
}
解决方法
正如Lucas在他的评论中所说,您可以创建UITableViewCell的自定义子类,并将操作附加到单元类。然后,您将消息从单元格转发到所有者表视图。 (您可能在单元类上需要一个委托属性,以便您知道将操作转发给谁。)
或者,您可以在cellForRowAt方法中配置IBAction:
func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ReusableCell",for: indexPath) as! TableViewCell
//other config code
//Make sure the slider doesn't already have the action attached.
if cell.gradeSlider.actions(forTarget: nil,forControlEvent: .valueChanged) == nil {
cell.gradeSlider.addTarget(self,action: @selector(actionSelector(:)),controlEvents: .valueChanged]
}
return cell
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。