[英]UIButton in UITableViewCell subclass not registering taps
我有一個“收藏夾”按鈕,希望將其單擊以將單元格標記為收藏夾。 單元也是可點擊的。
這是UITableViewCell的子類。 我已經添加了按鈕,但是我很難讓它調用目標動作。 換句話說,我點擊單元格中的按鈕,但是什么也沒有發生:
class ServerSelectionTableViewCell: UITableViewCell {
let isSelected = UIImage(named: "icon.png")
let unselected = UIImage(named: "star.png")
var favoriteButton: UIButton? = nil
var server : Server? = nil {
didSet{
if let theServer = server {
var server : String? = theServer.serverCode
self.textLabel?.text = serverCode
server?.isActive() { success in
self.accessoryType = success ? .Checkmark : .None
}
}
}
}
required init(coder aDecoder: NSCoder!) {
super.init(coder: aDecoder)
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: .Subtitle, reuseIdentifier: reuseIdentifier)
self.detailTextLabel?.textColor = UIColor.grayColor()
self.favoriteButton = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
self.favoriteButton?.setImage(unselected, forState: UIControlState.Normal)
self.favoriteButton?.setImage(isSelected, forState: UIControlState.Selected)
self.favoriteButton?.addTarget(self, action: Selector("buttonAction:"), forControlEvents: UIControlEvents.TouchDown)
setTranslatesAutoresizingMaskIntoConstraints(false)
self.favoriteButton?.userInteractionEnabled = true
self.contentView.addSubview(self.favoriteButton!)
}
func buttonAction(sender:UIButton!) {
println("Button tapped")
}
override func layoutSubviews() {
super.layoutSubviews()
self.favoriteButton?.frame = CGRectMake(10, 5, 35, 35)
self.textLabel?.frame = CGRectMake(55, 5, self.bounds.width, self.bounds.height)
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
從不調用buttonAction函數。 我已經在模擬器和設備上進行了嘗試,可以看到,當我點擊“收藏夾”按鈕時,未選中該單元格,但仍未調用該函數。
編輯:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let reuseId = "cell"
tableView.registerClass(ServerSelectionTableViewCell.self, forCellReuseIdentifier: reuseId)
var cell = tableView.dequeueReusableCellWithIdentifier(reuseId) as ServerSelectionTableViewCell
if let servers = getServers() {
let server = servers[indexPath.row]
cell.server = server
}
return cell
}
override func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
if let servers = getServers() {
let server = servers[indexPath!.row]
var cell = tableView.cellForRowAtIndexPath(indexPath) as ServerSelectionTableViewCell
println("Server selected \(server)")
}
}
因此,似乎按鈕正在注冊水龍頭,但行
println("Button tapped")
並沒有實際打印到控制台,所以我認為不是。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.