简体   繁体   中英

Swift Adding Button Action to TableView Cell

I'm trying to create a button within my custom tableview cell that has the action of creating a Parse class if it isn't already created and applying the text of the label of the row that the button clicked occurred as the value for the "following" column and set the "follower" column value as the username of the current loggedin user. Currently I have an error at the let usernameLabel in the addUser IBAction that my Class does not have a member named objectAtIndex . What is the best way to achieve what I'm looking for?

I have created the outlets in SearchUsersRegistrationTableViewCell.swift

import UIKit

class SearchUsersRegistrationTableViewCell: UITableViewCell {

    @IBOutlet var userImage: UIImageView!
    @IBOutlet var usernameLabel: UILabel!
    @IBOutlet weak var addUserButton: UIButton!


    override func awakeFromNib() {
        super.awakeFromNib()

        userImage.layer.borderWidth = 1
        userImage.layer.masksToBounds = false
        userImage.layer.borderColor = UIColor.whiteColor().CGColor
        userImage.layer.cornerRadius = userImage.frame.width/2
        userImage.clipsToBounds = true


    }

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

        // Configure the view for the selected state
    }



}

Here is my table functionality and the action that I tried to apply to my addUserButton :

import UIKit

class SearchUsersRegistrationViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {


    var userArray : NSMutableArray = []


    @IBOutlet var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self

        loadParseData()

        var user = PFUser.currentUser()




    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    func loadParseData() {

        var query : PFQuery = PFUser.query()

        query.findObjectsInBackgroundWithBlock {
            (objects:[AnyObject]!, error:NSError!) -> Void in

            if error == nil {

                if let objects = objects {

                    println("\(objects.count) users are listed")

                    for object in objects {

                        self.userArray.addObject(object)

                    }
                    self.tableView.reloadData()
                }
            } else {
                println("There is an error")
            }
        }
    }



    let textCellIdentifier = "Cell"

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {

        return 1

    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.userArray.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath: indexPath) as! SearchUsersRegistrationTableViewCell

        let row = indexPath.row

        var individualUser = userArray[row] as! PFUser
        var username = individualUser.username as String

        var profileImage = individualUser["profileImage"] as! PFFile

        profileImage.getDataInBackgroundWithBlock({
            (result, error) in

            cell.userImage.image = UIImage(data: result)

        })

        cell.usernameLabel.text = username

        cell.addUserButton.tag = row

        cell.addUserButton.addTarget(self, action: "addUser:", forControlEvents: .TouchUpInside)

        return cell

    }


    @IBAction func addUser(sender: UIButton){

        let usernameLabel = self.objectAtIndex(sender.tag) as! String

        var following = PFObject(className: "Followers")
        following["following"] = usernameLabel.text
        following["follower"] = PFUser.currentUser().username //Currently logged in user

        following.saveInBackground()
    }

    @IBAction func finishAddingUsers(sender: AnyObject) {
        self.performSegueWithIdentifier("finishAddingUsers", sender: self)

    }

}

I'm assuming the usernameLabel is on the same contentView as the UIButton sender. If that's the case you can add a tag to the usernameLabel and do this

let usernameLabel = sender.superview.viewWithTag(/*Put tag of label here*/)

I'm on a mobile so I don't know if viewWithTag is the right name of the method, but it's something similar.

hope this helps.

You are getting the error because you are using self instead of tableView

let usernameLabel = self.objectAtIndex(sender.tag) as! String
let usernameLabel = tableView.objectAtIndex(sender.tag) as! String

However, this will still give you an error because UITableViewCell cannot be cast as a String . This is a better option:

if let surtvc = tableView.objectAtIndex(sender.tag) as? SearchUsersRegistrationTableViewCell {
    // surtvc.usernameLabel...
    // the rest of your code goes here
}

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