我一直在写一个小型的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)
}
我所看到的:
还有标签正在消失的问题。
答案 0 :(得分:4)
dequeueReusableCellWithIdentifier 未获取上一个单元格,您应该使用 cellForRowAtIndexPath
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//get the cell,
let cell = tableView.cellForRowAtIndexPath(indexPath) as! SelectFriendTableViewCell
//do some work
}