Displaying a pop when button is tapped Swift

917 Views Asked by At

I have a XIB file with a custom cell, which has two buttons.

Basically, I want a dialogue box of some sort to pop up when the user taps the buttons which will inform them of details. I tried to display an alert view from the corresponding Swift file but as the XIB file inherits from a UITableViewCell I cannot present the alert controller. I also want the user to be able to edit the information displayed if possible (via alert controller).

In this context I want the button to display the user's Instagram and Twitter @usernames.

import UIKit

class SocialsTableViewCell: UITableViewCell {
    @IBOutlet var instagramButton: UIButton!
    @IBOutlet var twitterButton: UIButton!
    
    var instagramAt = ""
    var twitterAt = ""
    
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        // Configure the view for the selected state
    }
    
    
    @IBAction func instagramTapped(_ sender: UIButton) {
        print("iNSTA TAPPED")
    }
    
    @IBAction func twitterTapped(_ sender: UIButton) {
        print(twitterAt)
    }
}
1

There are 1 best solutions below

0
Raja Kishan On BEST ANSWER

You can not present anything from the cell class. You need UIViewController to present any controller.

There are many ways to achieve this.

Way 1: Present your controller on the root controller. Like this

@IBAction func twitterTapped(_ sender: UIButton) {
    UIApplication.shared.windows.first?.rootViewController?.present(/*Your controller*/, animated: true, completion: nil) //<==Here
}

Way 2: Present your controller on the top most controller. How to find top most controller.

@IBAction func twitterTapped(_ sender: UIButton) {
    UIApplication().topMostViewController()?.present(/*Your controller*/, animated: true, completion: nil) //<==Here
}

Way 3: Bind your action directly to the view controller class and present your controller on self. For this if you need index path you can check this. How to get indexPath?