2017-09-12 52 views
-2

我以編程方式在UICollectionViewCell的indexPath中創建了多個UIButton。現在我想打印「點擊添加到收藏夾」,但點擊UIButton後沒有打印任何東西。 UIButton確實查看除addTarget函數外的所有內容,而不是單擊。以編程方式在UICollectionViewCell的IndexPath中的多個UIButton,下一個addTarget不會單擊

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

+0

@AzmalTech必須有與按鈕視圖不addTarget問題,嘗試用唯一的目標首先添加簡單的按鈕,檢查視圖是否在屏幕上正確設計 – Abhishek

+0

@Abhishek視圖設計正確顯示 –

+0

您可以使用Xcode的視圖調試來檢查動態按鈕框以驗證其大小 – Abhishek

回答

2

嘗試用類似框架初始化按鈕:

let btn = UIButton(frame: CGRect(x: 10, y: 10, width: 50, height: 20)) 
+0

一切ok了UIButton的,只是addTarget不顯示任何信息後點擊按鈕 –

+0

我測試您的代碼段和它的工作對我來說很好。 –

+0

對不起!我忘了說「我加了多重的UIButton在一個collectionViewCell一個indexPath」 –

相關問題