简体   繁体   中英

Calling a function in another class Swift

I need to call this function. I need to receive the user identityString . How can i go about doing this?

class GeneralChatroom: UIViewController, 
                       UITableViewDataSource, 
                       UITableViewDelegate, 
                       UITextFieldDelegate, 
                       UITextViewDelegate {

    //Get Data of current cell that has been tapped
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {    
        let userIdentityString = generalRoomDataArr[indexPath.row].cellUserId

        print("Uid of cell Data: " + userIdentityString!)
        print("section: \(indexPath.section)")
        print("row: \(indexPath.row)")
    }

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


    let cell = tableView.dequeueReusableCell(withIdentifier: "cell")

    //Transform Data From ^ to load at the bottom
    tableView.transform = CGAffineTransform (scaleX: 1,y: -1);
    cell?.contentView.transform = CGAffineTransform (scaleX: 1,y: -1);
    cell?.accessoryView?.transform = CGAffineTransform (scaleX: 1,y: -1);

    //Set username label to display username
    let usernameLabel = cell?.viewWithTag(1) as! UILabel
    usernameLabel.text = generalRoomDataArr[indexPath.row].username

    //Set mesage TextView Label to display message in textView
    let messageLabel = cell?.viewWithTag(5) as! UITextView
    messageLabel.text = generalRoomDataArr[indexPath.row].message

    //TO DO: dont know if this actually works prob can delete
    messageLabel.setContentOffset(CGPoint(x: 0, y: 0), animated: false)


    //initialize UI Profile Image
    let imageView = cell?.viewWithTag(3) as! UIImageView

    //Make Porfile Image Cirlce
    imageView.layer.cornerRadius = imageView.frame.size.width/2
    imageView.clipsToBounds = true

    //Set timeStampLabel to current time AGO
    let timeStampLabel = cell?.viewWithTag(4) as! UILabel
    timeStampLabel.text = generalRoomDataArr[indexPath.row].timeStamp
    timeStampLabel.numberOfLines = 0


    //Loading and change of Usesrs profile image on chat cell
    let userProfileChatImage = generalRoomDataArr[indexPath.row].photoURL

    //Load profile image(on cell) with URL & Alamofire Library
        let downloadURL = NSURL(string: userProfileChatImage!)
        imageView.af_setImage(withURL: downloadURL as! URL)

    return cell!
}

}

But I need to call that function in a different class to get the userIdentityString . How can I do this? I need to call it in the Image Tapped function.

class GeneralChatroomTableViewCell: UITableViewCell {

    @IBOutlet weak var profileImageView: UIImageView!
    @IBOutlet weak var textViewHeight: NSLayoutConstraint!

    override func awakeFromNib() {
        super.awakeFromNib()

        // You must to use interaction enabled
        profileImageView.isUserInteractionEnabled = true
        profileImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(imageTapped(_:))))
    }

    func imageTapped(_ sender: UITapGestureRecognizer) {
        //first you need to call the function that reads the cell. Recieve the UID
        print("image tapped")
    }
}

maybe this will be more clear

func imageTapped(_ sender: UITapGestureRecognizer) {

        let userIDString = GeneralChatroom.tableView(userIdentityString: userIdentityString)

        print(userIDString)

        //first you need to call the function that reads the cell. Recieve the UID
        print("image tapped")


    }



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

        let userIdentityString = generalRoomDataArr[indexPath.row].cellUserId

        print("Uid of cell Data: " + userIdentityString!)
        print("section: \(indexPath.section)")
        print("row: \(indexPath.row)")

        //1.) If imageView touch is deteected
        //2.) Segua to new view controller by passing in the string UID(userIdentityString) of the cell
        //3.) Get database information based on the UID that is added(look at prevous methods)
        //      -might have to call this function and use separeate function
        //4.) Output data from database Users to represent a user profile



        //All you have to do is pass a UID (Check other Database methods to send UID)

        return userIdentityString!

    }

OK, as I stated in my comment this answer is not about calling another function from a swift class because you are trying to call a delegate function. I am not sure it can be guaranteed that function will have the expected value if called manually. What I would do is create a property on your TableViewCell to hold the userId .

class GeneralChatroomTableViewCell: UITableViewCell {

    @IBOutlet weak var profileImageView: UIImageView!
    @IBOutlet weak var textViewHeight: NSLayoutConstraint!

    // User Id
    var userId: String?

    override func awakeFromNib() {
        super.awakeFromNib()

        // You must to use interaction enabled
        profileImageView.isUserInteractionEnabled = true
        profileImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(imageTapped(_:))))
    }

    func imageTapped(_ sender: UITapGestureRecognizer) {

        //first you need to call the function that reads the cell. Recieve the UID
        print("image tapped")
        if let uid = self.userId {
            // Do whatever you want with userId
        }
    }
}

So I added an optional userId property on the TableViewCell. In order to populate that we will do it in the func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { delegate function. I am not sure what yours looks like since you didn't provide that code so I am just going on what it generally looks like and what your GeneralChatroomTableViewCell is.

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

    var cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(GeneralChatroomTableViewCell.self), for: indexPath) as! GeneralChatroomTableViewCell
    (cell as! GeneralChatroomTableViewCell).userId = generalRoomDataArr[indexPath.row].cellUserId
    return cell
}

This function is called whenever a cell is being created for display in the table. So now on creation of the cell we set the userId so that its always available for us whenever we need it.

And as stated in the comment above this is only useful if that data is available at the time of creation of the cell.

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