[英]Unrecognized Selector when Passing Parameter - UIButton in TableView Cell | Swift iOS
[英]iOS swift UIButton in TableView Cell
我有一個帶有自定義單元格的tableView
。 在我的自定義cell
我有一個喜歡的按鈕。 像巴頓我寫了一個函數來改變狀態.normal
至.selected
是這樣的:
FeedViewCell
class FeedViewCell: UITableViewCell {
@IBOutlet weak var likeButton: UIButton!
var likes : Bool {
get {
return UserDefaults.standard.bool(forKey: "likes")
}
set {
UserDefaults.standard.set(newValue, forKey: "likes")
}
}
override func awakeFromNib() {
super.awakeFromNib()
self.likeButton.setImage(UIImage(named: "like-btn-active"), for: .selected)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
@IBAction func likeBtnTouch(_ sender: AnyObject) {
print("press")
// toggle the likes state
self.likes = !self.likeButton.isSelected
// set the likes button accordingly
self.likeButton.isSelected = self.likes
}
}
FeedViewController:
class FeedViewController: UIViewController {
@IBOutlet var feedTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Register Cell Identifier
let feedNib = UINib(nibName: "FeedViewCell", bundle: nil)
self.feedTableView.register(feedNib, forCellReuseIdentifier: "FeedCell")
}
func numberOfSectionsInTableView(_ tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.feeds.count
}
func tableView(_ tableView: UITableView, heightForRowAtIndexPath indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "FeedCell", for: indexPath) as! FeedViewCell
return cell
}
}
但是我的問題是,當我點擊indexPath.row 0
單元格中的按鈕時, indexPath.row 3
單元格中按鈕的狀態也會改變。
我的錯誤在哪里?
謝謝
您並未發布所有代碼,但我可以告訴您,要使其正常工作, @IBAction func likeBtnTouch(_ sender: AnyObject) { }
定義必須位於FeedViewCell
類定義內,以使其對於特定的實例是唯一的。細胞。
根據經驗,在使用出隊的單元格時,我通常會確保單元格內的所有UI元素都填充在cellForRowAtIndexPath中。 此外,還應從外部來源進行設置。 現在不是來自單元格內部的屬性。 出隊單元會重用它們,如果設置不正確,則可能還有另一個單元的剩余物。
例如,在cellForRowAtIndexPath內部:
self.likeButton.isSelected = likeData[indexPath.row]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.