如何在Swift 3中将UIButton添加到我的UITableViewCell中?

问题描述:

我有一个现有的UITableView显示数据,并正常工作。如何在Swift 3中将UIButton添加到我的UITableViewCell中?

但是我现在想要添加一个信息按钮到这个UITableViewCell。

我将UIButton直接添加到故事板的TableViewCell中。然后我试图声明这个按钮是一个插座,但我得到了错误

“插座不能连接到重复的内容。”

我读围绕主题,并决定建立一个名为“新的子类

import UIKit 

class PersonalStatsTableViewCell: UITableViewCell { 

@IBOutlet weak var personalStatsInfoButton: UIButton! 

var selectedCellTitle: String? 


override func awakeFromNib() { 
    super.awakeFromNib() 

} 

override func setSelected(_ selected: Bool, animated: Bool) { 
    super.setSelected(selected, animated: animated) 

    // Configure the view for the selected state 
} 

} 

正如你可以看到我已经宣布的UIButton personalStatsInfoButton在这个子类。

随着越来越多的阅读围绕主题我相信我需要添加如下内容:

personalStatsInfoButton.tag = indexPath.row 
personalStatsInfoButton.addTarget(self, action: "infoButtonClicked", forControlEvents: UIControlEvents.TouchUpInside) 

然后有一个函数:

function infoButtonClicked(sender:UIButton){ 
     let infoCell = sender.tag 
     print (infoCell) 
} 

我的问题是我不知道我是否需要采取一切我现有的tableView代码,并将其转移到新的子类PersonalStatsTableViewCell或只是与信息按钮处理的部分。

下面是我现有的VC代码,它在添加这个新按钮之前首先处理TableView。

import UIKit 

class ShowCommunityViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { 

@IBOutlet weak var membersTableView: UITableView! 

@IBOutlet weak var communityName: UILabel! 
var communityIsCalled: String? 
var comIds = [String]() 
var communityId: Int? 


var selectedCellTitle: String? 
var cellId: Int? 

var communityPlayerIds = [String]() 
var communityPlayers = [String?]() 

override func viewDidLoad() { 

super.viewDidLoad() 

    communityName.text = (communityIsCalled) 
    self.membersTableView.delegate = self 
    self.membersTableView.dataSource = self 
    membersTableView.reloadData() 
} 

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 

    return self.communityPlayers.count 
} 

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

    let cell = tableView.dequeueReusableCell(withIdentifier: "PersonalStatsTableViewCell", for: indexPath as IndexPath) 
    cell.textLabel?.text = self.communityPlayers[indexPath.row] 
    cell.textLabel?.font = UIFont(name: "Avenir", size: 12) 
    cell.textLabel?.textColor = UIColor.white // set to any colour 
    cell.layer.backgroundColor = UIColor.clear.cgColor 

    return cell 

} 


func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 

    self.selectedCellTitle = self.communityPlayers[indexPath.row] 
    cellId = indexPath.row 


} 



override func viewDidAppear(_ animated: Bool) { 

    let myUrl = URL(string: "http://www.???.uk/???/specificCommunity.php?"); 
    var request = URLRequest(url:myUrl!); 
    request.httpMethod = "POST"; 

    let postString = "id=\(comIds[communityId!])"; 

    request.httpBody = postString.data(using: String.Encoding.utf8); 

    let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in 

     DispatchQueue.main.async 
      { 

       if error != nil { 
        print("error=\(error)") 
        return 
       } 

       do{ 
        let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject] 

        if let arr = json?["players"] as? [[String:String]] { 
         self.communityPlayerIds = arr.flatMap { $0["id"]!} 
         self.communityPlayers = arr.flatMap { $0["user_name"]!} 
        self.membersTableView.reloadData() 
         print ("names: ",self.communityPlayers) 
        } 

       } catch{ 
        print(error) 
       } 
     } 
     } 
    task.resume() 


} 

} 

你的代码,你在想什么是正确的,你只需要更改以下行。

除了Arun B所说的,你需要确保xcode知道什么样的类cell将属于。

let cell = tableView.dequeueReusableCell(withIdentifier: "PersonalStatsTableViewCell", for: indexPath as IndexPath) 

应该

let cell = tableView.dequeueReusableCell(withIdentifier: "PersonalStatsTableViewCell", for: indexPath as IndexPath) as! PersonalStatsTableViewCell 

如果自定义类设置不正确,会发生这种情况。确保PersonalStatsTableViewCell在故事板中设置为UITableViewCell的自定义类别。

enter image description here

你并不需要把所有的代码在你的类PersonalStatsTableViewCell你可以从ShowCommunityViewController管理你所需要做的是在你的cellForRowAt方法添加此

所有的东西
cell.personalStatsInfoButton.tag = indexPath.row 
cell.personalStatsInfoButton.addTarget(self, action: #selector(infoButtonClicked(sender:), forControlEvents: UIControlEvents.TouchUpInside) 

,并添加此功能

function infoButtonClicked(sender:UIButton){ 
     let infoCell = sender.tag 
     print (infoCell) 
} 
+1

正如Rajat所说,您可以在没有自定义表格视图单元类的情况下执行此操作。只需在cellForRowAt()方法中设置每个按钮的目标/操作即可。然后,您可以使用该标记返回索引路径,或者使用该按钮的frame.origin来确定包含该按钮的单元格的indexPath。 –