ios - समस्या का पता लगाने के बटन सेलफ़ोररॉव
swift uitableview (2)
मुझे यह पता लगाने की आवश्यकता है कि क्या बटन को UITableViewController में क्लिक किया गया है
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let LikesBtn = cell.viewWithTag(7) as! UIButton
}
पहला कदम: अपने कस्टम UITableViewCell के लिए उपवर्ग बनाएं, प्रोटोकॉल भी दर्ज करें।
कुछ इस तरह:
class MainViewCell: UITableViewCell {
@IBOutlet weak var testButton: UIButton!
@IBAction func testBClicked(_ sender: UIButton) {
let tag = sender.tag //with this you can get which button was clicked
}
}
अपने TableViewController में, सुनिश्चित करें कि यह आपके द्वारा बनाए गए प्रोटोकॉल "MyTableViewCellDelegate" के अनुरूप है।
बेहतर समझ के लिए नीचे दिए गए कोड को देखें।
class MainController: UIViewController, UITableViewDelegate, UITableViewDataSource, {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! MainViewCell
cell.testButton.tag = indexPath.row
return cell
}
}
यहाँ मेरा उपयोग है:
पहले बटन को एक
Outlet
रूप में आरंभीकृत करें और अपने
TableViewCell
पर इसकी
action
protocol MyTableViewCellDelegate: class {
func onButtonPressed(_ sender: UIButton, indexPath: IndexPath)
}
class MyTableViewCell: UITableViewCell {
@IBOutlet var cellButton: UIButton!
var cellIndexPath: IndexPath!
weak var delegate: MyTableViewCellDelegate!
override func awakeFromNib() {
super.awakeFromNib()
cellButton.addTarget(self, action: #selector(self.onButton(_:)), for: .touchUpInside)
}
func onButton(_ sender: UIButton) {
delegate.onButtonPressed(sender, indexPath: cellIndexPath)
}
}
फिर आप मुख्य नियंत्रक में सेलफोरो फंक्शन में बटन के टैग को इस तरह से इनिशियलाइज़ करें:
class MyTableViewController: UITableViewController, MyTableViewCellDelegate {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath) as? MyTableViewCell {
cell.cellIndexPath = indexPath
cell.delegate = self
return cell
} else {
print("Something wrong. Check your cell idetifier or cell subclass")
return UITableViewCell()
}
}
func onButtonPressed(_ sender: UIButton, indexPath: IndexPath) {
print("DID PRESSED BUTTON WITH TAG = \(sender.tag) AT INDEX PATH = \(indexPath)")
}
}