-2

I made multiple UIButton in a indexPath in a UICollectionViewCell programmatically. now i want to print "clicked add to favourite" but it is not printing anything after click UIButton. the UIButton does view everything except addTarget function not click.

import UIKit

//**UICollectionViewCell**
class DescriptionCell: UICollectionViewCell, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {


    override init(frame: CGRect) {
        super.init(frame: frame)


        setupCell()

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }



    lazy var addToCart: UIButton = {

        let btn = UIButton()
        btn.setTitle("Add to favourite", for: .normal)
        btn.isUserInteractionEnabled = true
        btn.setTitleColor(.white, for: .normal)

        btn.backgroundColor = UIColor.orange
        btn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 8)
        btn.titleLabel?.textAlignment = .right

        // addToCart not click
        btn.addTarget(self, action: #selector(addToCartTarget), for: .touchUpInside)

        btn.layer.cornerRadius = 12

        return btn
    }()




    func setupCell() {



        addSubview(addToCart)



        addConstraintsWithFormat("H:|-80-[v0]-80-|", views: addToCart)
             addConstraintsWithFormat("V:|-380-[v0(25)]|", views: addToCart)


    }



    func addToCartTarget() {

        print("you clicked add to favourite")
    }




}

enter image description here

Quiet Islet
  • 536
  • 1
  • 8
  • 28

1 Answers1

2

Try initializing button with frame like:

let btn = UIButton(frame: CGRect(x: 10, y: 10, width: 50, height: 20))
laxman khanal
  • 998
  • 1
  • 8
  • 18
  • everything is ok of UIButton, just addTarget does not print anything after click button – Quiet Islet Sep 12 '17 at 07:05
  • I tested your code snippet and its working fine for me. – laxman khanal Sep 12 '17 at 07:07
  • sorry! i forget to say "i Added multiple UIButton in a indexPath in a collectionViewCell" – Quiet Islet Sep 13 '17 at 04:49
  • Brother! i have been unable to add pushViewController with this button in collectionViewCell. but added presentViewController by this code `self.window?.rootViewController?.present(ViewController(), animated: true, completion: nil)` – Quiet Islet Sep 16 '17 at 11:53
  • You can push view controllers to navigation controllers only, `navigationController?.pushViewController(activityTimesTVC, animated: true)`. For this you have to embed yor viewcontroller to navigationcontroller in storyboard. Go to Editor -> Embed In -> Navigation Controller. – laxman khanal Sep 18 '17 at 08:21