当按下自定义单元格中的按钮时,我正在使用自定义单元格委托来调用函数。我想根据自定义单元格类的布尔变量将按钮的图像更改为特定图像。
我知道如何在没有委托的情况下执行此操作,但是我也希望在按下按钮时显示警报视图,而我无法在自定义单元格类中执行此操作。
我遇到的问题是我在尝试访问委托函数中的自定义单元格属性时出现EXC_BAD_ACCESS错误。这是我的自定义类的代码:
import UIKit
protocol ProfileHeaderCellDelegate: class {
func follow(sender:ProfileHeaderCell)
}
class ProfileHeaderCell: UITableViewCell {
var followTapped = false
var delegate : ProfileHeaderCellDelegate!
@IBOutlet var profilePic: UIImageView!
@IBOutlet var followButton: UIButton!
@IBAction func followButtonTapped(sender: AnyObject) {
delegate?.follow(self)
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.profilePic.layer.cornerRadius = self.profilePic.frame.size.width / 2;
self.profilePic.clipsToBounds = true;
}
@IBOutlet var albumArt: UIImageView!
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
这是来自包含单元格的表视图控制器中的函数调用:
func follow(sender: ProfileHeaderCell){
if(sender.followTapped == false){
sender.followButton.imageView?.image = UIImage(named: "img1")
sender.followTapped = true
}else if(sender.followTapped == true){
let unfollowAlert = UIAlertController(title: "", message:"Would you like to unfollow this User?", preferredStyle: .Alert)
let unfollow = UIAlertAction(title: "Yes, Unfollow this User", style: .Destructive){(ACTION) in
print("unfollow tapped")
sender.followButton.imageView!.image = UIImage(named: "img2")
}
let cancel = UIAlertAction(title: "Cancel", style: .Cancel){(ACTION) in
print("cancel tapped")
}
unfollowAlert.addAction(unfollow)
unfollowAlert.addAction(cancel)
self.presentViewController(unfollowAlert, animated: true, completion: nil)
}
}
委托函数的第一行发生错误访问错误:
if(sender.followTapped == false){
如何从自定义单元格对象中正确访问变量?
答案 0 :(得分:0)
我意识到我的错误在我的cellForRowAtIndexPath
方法中。问题是除了在点击按钮时调用委托方法(通过我的自定义单元类中的IBAction),我还在cellForRowAtIndexPath
方法中有以下行:
cell1.followButton.addTarget(self, action: "follow:", forControlEvents: .TouchUpInside)
我想错误的访问是因为某种方式调用了相同的“跟随”方法,但是从主视图控制器内部,这意味着发送方单元格从未作为参数传递。