-1

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.")
}    

1 Answer 1

1

The problem is vwContainer. There are two issues:

  • It has no size (unless you are sizing it in code you failed to post).
  • It is added as a subview to the cell. You must never add a subview to a cell. You must add it only to the cell's contentView.

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

2
  • Worked! Regarding the adding an image to a button, this is better, right? b.setImage(UIImage(named: "theicon"), for: .normal) Commented Jul 6 at 11:29
  • It is better, yes.
    – matt
    Commented Jul 6 at 14:22

Not the answer you're looking for? Browse other questions tagged or ask your own question.