繁体   English   中英

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

[英]How do I add a UIButton into my UITableViewCell in Swift 3?

我有一个现有的UITableView,它可以显示数据并且工作正常。

但是,我现在想在此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()


}

}

您不需要在类PersonalStatsTableViewCell放置任何代码,就可以从ShowCommunityViewController管理所有事情, 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)
}

如果自定义类未正确设置,则会发生这种情况。 确保将PersonalStatsTableViewCell设置为情节UITableViewCell中的UITableViewCell的Custom类。

在此处输入图片说明

您的代码和您的想法是正确的,您只需要更改以下行。

除了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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM