我一直在编写一个小型 Swift 应用程序。 我现在正在使用 tableview 并尝试选择一行,更改图像并取消选择该行。
我的自定义 UITableViewCell
类如下所示:
class SelectFriendTableViewCell: UITableViewCell {
@IBOutlet weak var friendNameLabel: UILabel!
@IBOutlet weak var friendSelectedImage: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
我的 TableViewController
有这些功能:
构建细胞:
//Build the cell
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("SelectFriend", forIndexPath: indexPath) as! SelectFriendTableViewCell
//Default image is unselected
cell.friendSelectedImage.image = UIImage(named: "unselected")
//Get the label text
cell.friendNameLabel.text = friendList[indexPath.row]
return cell
}
选择单元格时执行操作(didSelectRowAtIndexPath
)
//Cell was selected
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let cell = tableView.dequeueReusableCellWithIdentifier("SelectFriend", forIndexPath: indexPath) as! SelectFriendTableViewCell
//Check wheter the cell is or not selected
if(cell.friendSelectedImage.image == UIImage(named: "unselected"))
{
//if it's unselected, select it and add the user to the invited list
cell.friendSelectedImage.image = UIImage(named: "selected")
//Add to the invited list, the label can't be null
invitedList += [cell.friendNameLabel.text!]
}
else if(cell.friendSelectedImage.image == UIImage(named: "selected"))
{
//if it's selected, unselect it and remove the user from the invited list
cell.friendSelectedImage.image = UIImage(named: "unselected")
//Find the invited in the array and remove it
for(var i=0; i < invitedList.count; i++)
{
if(invitedList[i] == cell.friendNameLabel.text!)
{
invitedList.removeAtIndex(i)
break
}
}
}
else
{
print("error geting image")
}
//Trying to deselect the row, doesn't seem to be working
tableView.deselectRowAtIndexPath(indexPath, animated: false)
}
我所看到的:
还有标签消失的问题。
最佳答案
dequeueReusableCellWithIdentifier 没有得到之前的cell,应该使用cellForRowAtIndexPath
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//get the cell,
let cell = tableView.cellForRowAtIndexPath(indexPath) as! SelectFriendTableViewCell
//do some work
}
关于ios - deselectRowAtIndexPath 什么都不做,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34713405/