[英]iOS swift UIButton in TableView Cell
I have a tableView
with custom cell. 我有一个带有自定义单元格的
tableView
。 in my custom cell
I have a like button. 在我的自定义
cell
我有一个喜欢的按钮。 for like Button I wrote a function to change state from .normal
to .selected
like this: 像巴顿我写了一个函数来改变状态
.normal
至.selected
是这样的:
FeedViewCell 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 : 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
}
}
But my problem is when I tap like button in cell with indexPath.row 0
the state of button in cell with indexPath.row 3
change state too. 但是我的问题是,当我点击
indexPath.row 0
单元格中的按钮时, indexPath.row 3
单元格中按钮的状态也会改变。
where is my mistake? 我的错误在哪里?
thanks 谢谢
您并未发布所有代码,但我可以告诉您,要使其正常工作, @IBAction func likeBtnTouch(_ sender: AnyObject) { }
定义必须位于FeedViewCell
类定义内,以使其对于特定的实例是唯一的。细胞。
As a rule of thumb, I normally ensure that all the UI elements inside my cell are populated in cellForRowAtIndexPath when using dequeued cells. 根据经验,在使用出队的单元格时,我通常会确保单元格内的所有UI元素都填充在cellForRowAtIndexPath中。 Also it should be set from an external source.
此外,还应从外部来源进行设置。 Iow not from a property inside the cell.
现在不是来自单元格内部的属性。 Dequeuing cells reuse them, and if not setup properly, it might have some leftovers from another cell.
出队单元会重用它们,如果设置不正确,则可能还有另一个单元的剩余物。
For example, inside cellForRowAtIndexPath: 例如,在cellForRowAtIndexPath内部:
self.likeButton.isSelected = likeData[indexPath.row]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.