How to add uibutton action in a collection view cell?

后端 未结 5 1040
走了就别回头了
走了就别回头了 2021-01-03 01:03

So I have this collection view with cells containing an edit button, located on the upper right corner. How do I wire up an action into it?

I tried adding <

5条回答
  •  执笔经年
    2021-01-03 01:38

    May be needful for you-

    Write this code in cellForItemAtIndexPath

    Swift 2.X

    let editButton = UIButton(frame: CGRectMake(0, 20, 40,40))
    editButton.setImage(UIImage(named: "editButton.png"), forState: UIControlState.Normal)
    editButton.addTarget(self, action: #selector(editButtonTapped), forControlEvents: UIControlEvents.TouchUpInside)
    
    cell.addSubview(editButton)
    

    Swift 3.X

    let editButton = UIButton(frame: CGRect(x:0, y:20, width:40,height:40))
    editButton.setImage(UIImage(named: "editButton.png"), for: UIControlState.normal)
    editButton.addTarget(self, action: #selector(editButtonTapped), for: UIControlEvents.touchUpInside)
    
    cell.addSubview(editButton)
    

    And perform your action-

    override func viewDidLoad() {
           super.viewDidLoad()
    }
    
    @IBAction func editButtonTapped() -> Void {
        print("Hello Edit Button")
    }
    

提交回复
热议问题