Reputation: 97
I am new in swift and I am facing problem when I click on button which is in viewForFooterInSection
my code is like this
In viewForFooterInSection
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let footerview = Bundle.main.loadNibNamed("TimeSheetFooterTableViewCell", owner: self, options: nil)?.first as! TimeSheetFooterTableViewCell
let dictFeeStats = arrFinancialYears[section] as? [String:Any]
footerview.lblTimeSheetFooterID.text = dictFeeStats?["staff_timesheet_id"] as? String
footerview.btnAccept.tag = section
footerview.btnAccept.addTarget(self, action: #selector(btnAcceptClick), for: .touchUpInside)
return footerview
}
On Button Click
@objc func btnAcceptClick(_ sender: UIButton)
{
let index = IndexPath(row: sender.tag, section: 0)
let cell: TimeSheetFooterTableViewCell = self.tblview.cellForRow(at: index) as! TimeSheetFooterTableViewCell
let comment = cell.lblTimeSheetFooterID.text
print("buttonPressed ! \(sender.tag)")
}
How can I get TimeSheetFooterTableViewCell value in comment variable. Thanks in Advance!
Upvotes: 0
Views: 272
Reputation: 664
usually the user interactions placed in the cell. And after tap, tapped cell informs the tablewView through callbacks.
This a cell code:
class TimeSheetFooterTableViewCell: UITableViewCell {
var btnAccept: UIButton!
var lblTimeSheetFooterID: UITextView!
override func awakeFromNib() {
super.awakeFromNib()
btnAccept = UIButton()
btnAccept.addTarget(self, action: #selector(btnAcceptClick), for: .touchUpInside)
}
//Callback for communication between cell and tableView
var btnDidTap: ((String) -> Void)?
@objc func btnAcceptClick(_ sender: UIButton) {
btnDidTap?(lblTimeSheetFooterID.text ?? "")
}
}
This is a footer function in tableView delegate:
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let footerview = Bundle.main.loadNibNamed("TimeSheetFooterTableViewCell", owner: self, options: nil)?.first as! TimeSheetFooterTableViewCell
let dictFeeStats = arrFinancialYears[section] as? [String: Any]
footerview.btnDidTap = { comment in
print("section number: \(section) DID TAP!")
}
return footerview
}
Upvotes: 0
Reputation: 16381
Use footerView(forSection:)
method instead of cellForRow(at:)
.
Replace:
let cell: TimeSheetFooterTableViewCell = self.tblview.cellForRow(at: index) as! TimeSheetFooterTableViewCell
With:
let footerView = tblview.footerView(forSection: sender.tag) as! TimeSheetFooterTableViewCell
Upvotes: 0
Reputation: 953
You can add a closure in TimeSheetFooterTableViewCell
that accepts a string. When button is tapped, call that closure with the textview's text.
var acceptButtonTapped: ((String?) -> ())?
@IBAction func btnAcceptClick(_ sender: UIButton) {
acceptButtonTapped?(txtview.text)
}
In your tableView(_ tableView: UITableView, viewForFooterInSection
, get the text from the callback.
footerview.acceptButtonTapped = { text in
print(text)
}
Upvotes: 1