swiftuitableviewbuttonuikitimageview

In Swift UIKit, how to add two button images inside a table cell?


I need two images buttons to be clickable inside a certain cell (not all cells), instead of the text. How can I do this? I have the cell extension, and the image "the_icon" exists (I can see it display on the screen), but I can't seem to get the trigger (fja()) working on the button like this:

class ChatCell: UITableViewCell {
    ...
    
    @IBOutlet var b: UIButton!
    
    let vwContainer: UIView = {
        let vw = UIView()
        vw.backgroundColor = APP_YELLOW_COLOR
        vw.layer.cornerRadius = 8.0
        vw.clipsToBounds = true
        return vw
    }()


    let lblMessage: UILabel = {
        let ic = UILabel()
        ic.font = .appFontWithSize(size: 14.0)
        ic.numberOfLines = 0
        ic.lineBreakMode = .byWordWrapping
        return ic
    }()
    ....
}

Inside the init, I have tried to put a button with imageview, and tie it to a function fja() but it doesn't seem to work. The fja() is just a function inside ChatCell which just has one print() in it. What am I missing:

override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
        
    backgroundColor = .clear
    selectionStyle = .none
        
    addSubview(vwContainer)
    addSubview(messageStatusImage)
        
    let b = UIButton()
    b.setImage(UIImage(named: "the_icon"), for: .normal)
    b.frame.size = CGSize(width: 50.0, height: 50.0)
    b.addSubview(i)
        
    //lblMessage.addSubview(b) I TRIED ALSO THIS
        
    b.addTarget(self, action: #selector(fja), for: .touchUpInside)
    vwContainer.addSubview(lblMessage)
    vwContainer.addSubview(b)
        
}

// @objc func fja() { I TRIED ALSO THIS, declaring it as @objc
@IBOutlet func fja() {
    print("this is never reached.")
}    

Solution

  • The problem is vwContainer. There are two issues:

    (The button itself also seems to have no size, plus what you are doing is not how to give a button an image. But there is no point fixing that until you have fixed its superview.)