Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

ios - Swift 3- How to get button in UICollectionViewCell work

I am trying to implement an Edit button inside a cell.

Please refer to image:
enter image description here

What I done so far:

MainController:

class MainController: UICollectionViewController, UICollectionViewDelegateFlowLayout  {
  let imgCellId = "imgCellId"

  override func viewDidLoad() {
    collectionView?.backgroundColor = .white
    collectionView?.register(ImgItemCell.self, forCellWithReuseIdentifier: imgCellId)
  }

  override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {   
      let cell = collectionView.dequeueReusableCell(withReuseIdentifier: imgCellId, for: indexPath) as! ImgItemCell
      cell.editButton.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)

      return cell
  }

  func buttonPressed(){
    print("buttonPressed !")
  }

}

ImgItemCell:

import Material

class ImgItemCell: UICollectionViewCell{

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

       setupViews()
   }
   ...
   let editButton: RaisedButton = {
       let button = RaisedButton(title: "Edit", titleColor: .black) return button
   }()

  func setupViews(){
     ...
     addSubview(editButton)
     ...
  }

}

Result: The button is not clickable. No log is printed when clicking on the button.

In android, I have done this by OnClickListener of button to perform action for each row. How can I do the same in Swift 3?

Solution: (it's working for me)

Hi all thank you for all suggestions, they’re more less the hint for me to come to the solution.

The root cause of my problem is view hierarchy (as @DatForis pointed out)

Explanation: I want a cell contains image and a layout of buttons so that I had view hierarchy as below

override func setupViews() {
    super.setupViews()

    addSubview(imgView)
    addSubview(buttonLayout)
    buttonLayout.addSubView(buttonList)
            buttonList.addSubview(editButton)
            buttonList.addSubview(shareButton)
  }

this hierarchy somehow blocked the click event of button.

Therefore, I changed a bit in hierarchy

  override func setupViews() {
    super.setupViews()

    addSubview(imgView)
    addSubview(buttonLayout)
            buttonLayout.addSubview(editButton)
            buttonLayout.addSubview(shareButton)
   }

and BAM ! it worked like a charm.

In fact, I need a proper explanation about why the hierarchy impact to children view.

By the way, I think most replies here are workable solution, but I selected @DonMag as final answer, because it’s clean and clear with a cool callback to Controller.

But again, my root problem is from view hierarchy.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A very reliable and flexible pattern is to assign a "Callback Closure" to your cell. Put your button action handler inside the cell, and have it "call back" to the view controller.

Here is a basic example (you should be able to implement it with your custom cell with no problem):

//
//  CViewWithButtonCollectionViewController.swift
//  SWTemp2
//
//  Created by Don Mag on 6/5/17.
//  Copyright ? 2017 DonMag. All rights reserved.
//

import UIKit

private let reuseIdentifier = "ImgItemCell"

class ImgItemCell: UICollectionViewCell {

    // this will be our "call back" action
    var btnTapAction : (()->())?

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

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupViews()
    }

    let editButton: UIButton = {
        let button = UIButton(type: UIButtonType.system)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.backgroundColor = .white
        button.setTitle("Edit", for: .normal)
        return button
    }()

    func setupViews(){

        // add a button
        addSubview(editButton)

        editButton.centerXAnchor.constraint(equalTo: contentView.centerXAnchor).isActive = true
        editButton.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true

        // add the touchUpInside target
        editButton.addTarget(self, action: #selector(btnTapped), for: .touchUpInside)

    }

    @objc func btnTapped() {
        print("Tapped!")

        // use our "call back" action to tell the controller the button was tapped
        btnTapAction?()
    }

}

class CViewWithButtonCollectionViewController: UICollectionViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        if let layout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout {
            layout.itemSize = CGSize(width: 300, height: 100)
        }

    }

    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 10
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! ImgItemCell

        cell.backgroundColor = .red

        // set a "Callback Closure" in the cell
        cell.btnTapAction = {
            () in
            print("Edit tapped in cell", indexPath)
            // start your edit process here...
        }

        return cell
    }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...