【问题标题】:How to create dynamic button action in collection view in swift?如何快速在集合视图中创建动态按钮操作?
【发布时间】:2023-03-20 23:20:01
【问题描述】:
    import UIKit
    import Alamofire


    class ViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,StarSelect {        
    var user_Menu = [DynamicMenu]()
    var user_Id = [Int]()

    @IBOutlet weak var buton: UIButton!

    // UITableViewDelegate,UITableViewDataSource

    @IBOutlet weak var dashBoardCollectionView: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()
        getData()                       
    }        

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return user_Menu.count
    }

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

        cell.nameTitle.text = user_Menu[indexPath.row].menuName            
        cell.delegate = self
        cell.indexPath = indexPath            
        return cell                     
    }


    func tapStar(indexPath: IndexPath, star: Int) {
       // let cell = ctsHistoryTableBiew.cellForRow(at: indexPath) as! CtcHistoryCell

        let cell = dashBoardCollectionView.cellForItem(at: indexPath) as! DasboardCell            
        if star == 1 {                
            print("profile")

        }            
        if star == 5 {                
            print("Attndnce")
        }            
    }


    func getData(){                

        let url = "https://www.url.com"
        Alamofire.request(url, method: .get, parameters:nil, encoding: URLEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in
            switch(response.result) {
            case .success(_):                    
                if let data = response.result.value{                        
                    let json = response.result.value as? [String: Any]
                    print("json",json)
                    let responseStatus = json!["responseStatus"] as! Bool
                    let responseText  = json!["responseText"] as! String

                    if (responseStatus == true){

                        let responseData = json!["responseData"] as! [Any]
                        var index = 0
                        while index < responseData.count{
                            let responseArray = responseData[index] as! [String: Any]
                            let menuID = responseArray["MenuItemId"] as? Int
                            let menuName = responseArray["MenuItemName"] as? String

                            let folderApppend = DynamicMenu()
                            folderApppend.menuItemId = "\(menuID!)"
                            folderApppend.menuName = menuName
                            self.user_Menu.append(folderApppend)                                
                            self.user_Id.append(menuID!)                                
                            index += 1                                                             
                            print("userID",self.user_Id)                            
                        }

                        DispatchQueue.main.async {                                
                            self.dashBoardCollectionView.reloadData()                                
                        }                                                        
                    }                        
                }
                break                    
            case .failure(_):                   
                print("faliure",response.result.error!)
             //   self.displayAlertMessage(messageToDisplay: "Something Wrong Please try again")
                break

            }
        }               
    }              
}

import UIKit

protocol StarSelect {
    func tapStar(indexPath: IndexPath, star: Int)
}        

class DasboardCell: UICollectionViewCell {        

    @IBOutlet weak var nameTitle: UILabel!                      
    @IBOutlet weak var profileButton: UIButton!

    var delegate: StarSelect?
    var indexPath: IndexPath?

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }        

    @IBAction func tapButton(_ sender: UIButton) {            
         delegate?.tapStar(indexPath: indexPath!, star: sender.tag)                        
    }        
}        

class DynamicMenu{        
    var menuItemId:String?
    var menuName:String?        
}

image

【问题讨论】:

  • 当你可以使用委托方法didSelectItemAtUICollectionView 时为什么要添加动态操作

标签: ios swift swift3


【解决方案1】:

@Sahid Reza 尝试使用响应者链 - The Responder Chain

 @objc
 protocol DasboardCellButtonAction: AnyObject {

        func tapButtonDidPressAction(_ sender: DasboardCell)
 }

class DasboardCell: UICollectionViewCell {

    // MARK: - UI Action methods
    @objc
    fileprivate func tabButtonAction(_ aSender: UIButton) {
        UIApplication.shared.sendAction(

            #selector(DasboardCellButtonAction.tapButtonDidPressAction(_:)), to: nil, from: self, for: nil)
    }
}

     extension UIViewController: DasboardCellButtonAction {
        func tapButtonDidPressAction(_ sender: DasboardCell) {

           if let object = sender.selectedObject {
              // present the detail view controller
            }
        }
    }

【讨论】:

    【解决方案2】:

    动态操作按钮是什么意思?

    这样的?

    //... 
        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
                let cell = collectionView.dequeueReusableCell(withReuseIdentifier:"DasboardCell",for: indexPath) as! DasboardCell
    
                cell.nameTitle.text = user_Menu[indexPath.row].menuName
                cell.someCustomAction = { [weak self] in
                    print(self?.user_Menu[indexPath.row].menuName)
                }
                return cell
            }
    
    //... 
    
     class DasboardCell: UICollectionViewCell {
    
        @IBOutlet weak var nameTitle: UILabel!
        @IBOutlet weak var profileButton: UIButton!
    
        var someCustomAction: (() -> Void)?
    
        override func awakeFromNib() {
            super.awakeFromNib()
            // Initialization code
        }
    
        @IBAction func tapButton(_ sender: UIButton) {
            someCustomAction?()
        }
       }
    
    //... 
    

    一些观察:

    • 委托通常应该很弱(由于内存泄漏)
    • 使用标签是一个不好的迹象(总是根据你的情况做一些自定义的事情)
    • 您不需要在单元格上保留索引路径(您可以使用 indexPathForCell 方法)

    【讨论】:

      猜你喜欢
      • 2018-10-08
      • 1970-01-01
      • 2019-07-18
      • 1970-01-01
      • 1970-01-01
      • 2021-12-04
      • 1970-01-01
      • 1970-01-01
      • 2021-12-11
      相关资源
      最近更新 更多