简体   繁体   中英

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

I have an existing UITableView that displays data and is working fine.

However I now want to add an info button into this UITableViewCell.

I added the UIButton directly into the TableViewCell in storyboard. I then tried to declare this button as an outlet but I got the error

"Outlets cannot be connected to repeating content."

I read around the subject and decided to create a new subclass called "

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
}

}

As you can see I have declared the UIButton personalStatsInfoButton in this sub-class.

With more reading around the subject I believe I need to add something like:

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

and then have a function:

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

My issue is I don't know whether I need to take all my existing tableView code and transfer it into the the new sub-class PersonalStatsTableViewCell or just the parts that deal with the info button.

Below is my existing VC code that initially deals with the TableView prior to adding in this new button.

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()


}

}

You don't need to put any code in your class PersonalStatsTableViewCell you can manage all the things from ShowCommunityViewController what you need to done is in your cellForRowAt method add this

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

and add this function

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

This happens if the custom class is not set up properly. Make sure that PersonalStatsTableViewCell is set as the Custom class of the UITableViewCell in your storyboard.

在此处输入图片说明

Your code and what you are thinking is correct, you just need to change the following line.

Apart from what Arun B has said, you need to make sure xcode knows what kind of class cell will belong to.

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

should be

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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