为什么UICollectionView根本没有响应?

时间:2018-04-26 06:47:46

标签: ios swift uicollectionview

我在ViewController中设置UICollectionView。但是,它不会响应任何用户交互,didSelectItemAt函数没有被调用,我无法滚动它。

我已在viewDidLoad()内正确设置了DataSource和Delegate。这是我的代码:

class WelcomeController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

let padding: CGFloat = 30
var sources = [Source]()
let sourceCellId = "sourceCellId"

func fetchSources() {
    ApiSourceService.sharedInstance.fetchSources() { (root: Sources) in
        self.sources = root.source
        self.sourceCollectionView.reloadData()
    }
}

let backgroundImage: UIImageView = {
   let iv = UIImageView()
    iv.image = UIImage(named: "background")
    iv.contentMode = .scaleAspectFill
    iv.translatesAutoresizingMaskIntoConstraints = false
    iv.clipsToBounds = false
    return iv
}()

let overlayView: UIView = {
   let view = UIView()
    view.translatesAutoresizingMaskIntoConstraints = false
    view.backgroundColor = .white
    return view
}()

let logo: UIImageView = {
    let iv = UIImageView()
    iv.image = UIImage(named: "mylogo")
    iv.translatesAutoresizingMaskIntoConstraints = false
    iv.clipsToBounds = false
    return iv
}()

let defaultButton: UIButton = {
    let ub = UIButton()
    ub.translatesAutoresizingMaskIntoConstraints = false
    ub.setTitle("Inloggen met E-mail", for: .normal)
    ub.setImage(UIImage(named: "envelope"), for: .normal)
    ub.imageEdgeInsets = UIEdgeInsetsMake(15, 0, 15, 0)
    ub.imageView?.contentMode = .scaleAspectFit
    ub.contentHorizontalAlignment = .left
    ub.titleLabel?.font = UIFont.init(name: "Raleway-Regular", size: 16)
    ub.backgroundColor = .cuOrange
    return ub
}()

let continueWithoutButton: UIButton = {
    let ub = UIButton()
    ub.translatesAutoresizingMaskIntoConstraints = false

    let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: "Doorgaan zonder in te loggen")
    let textRange = NSMakeRange(0, attributedString.length)
    attributedString.setColor(color: .cuOrange, forText: "Doorgaan")
    ub.setAttributedTitle(attributedString, for: .normal)

    ub.contentHorizontalAlignment = .center
    ub.titleLabel?.font = UIFont.init(name: "Raleway-Regular", size: 16)
    ub.titleLabel?.textColor = .white
    return ub
}()


let sourceCollectionView: UICollectionView = {
   let layout = UICollectionViewFlowLayout()
    let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
    cv.translatesAutoresizingMaskIntoConstraints = false
    cv.backgroundColor = .white
    return cv
}()



let termsButton: UIButton = {
    let ub = UIButton()
    ub.translatesAutoresizingMaskIntoConstraints = false

    let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: "Met het maken van een account \nof bij inloggen, ga ik akkoord \nmet servicevoorwaarden.")
    let textRange = NSMakeRange(0, attributedString.length)
    attributedString.setColor(color: .cuOrange, forText: "servicevoorwaarden")
    ub.setAttributedTitle(attributedString, for: .normal)

    ub.contentHorizontalAlignment = .center
    ub.contentVerticalAlignment = .bottom
    ub.titleLabel?.lineBreakMode = .byWordWrapping
    ub.titleLabel?.font = UIFont.init(name: "Raleway-Regular", size: 14)
    ub.titleLabel?.textColor = .white
    ub.titleLabel?.textAlignment = .center
    return ub
}()

override func viewDidLoad() {
    super.viewDidLoad()

    fetchSources()

    sourceCollectionView.dataSource = self
    sourceCollectionView.delegate = self
    sourceCollectionView.register(SourceCell.self, forCellWithReuseIdentifier: sourceCellId)

    view.addSubview(backgroundImage)
    view.addSubview(overlayView)
    backgroundImage.addSubview(termsButton)
    backgroundImage.addSubview(logo)
    backgroundImage.addSubview(sourceCollectionView)

    backgroundImage.widthAnchor.constraint(lessThanOrEqualToConstant: 375).isActive = true
    backgroundImage.heightAnchor.constraint(lessThanOrEqualToConstant: 667).isActive = true
    backgroundImage.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    backgroundImage.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true



    logo.centerXAnchor.constraint(equalTo: backgroundImage.centerXAnchor).isActive = true
    logo.topAnchor.constraint(equalTo: backgroundImage.topAnchor, constant: padding).isActive = true
    logo.widthAnchor.constraint(equalToConstant: 107).isActive = true
    logo.heightAnchor.constraint(equalToConstant: 100).isActive = true

    sourceCollectionView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    sourceCollectionView.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -(padding*1.5)).isActive = true
    sourceCollectionView.topAnchor.constraint(equalTo: logo.bottomAnchor, constant: padding).isActive = true
    sourceCollectionView.bottomAnchor.constraint(equalTo: termsButton.topAnchor, constant: -(padding*2)).isActive = true

    termsButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -padding).isActive = true
    termsButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    termsButton.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -(padding*2)).isActive = true
    termsButton.heightAnchor.constraint(equalToConstant: 40).isActive = true

    sourceCollectionView.reloadData()

}

@objc func closeWelcomeController() {

    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    appDelegate.switchViewControllers()

    self.dismiss(animated: true, completion: {

    })

}


func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let width = self.sourceCollectionView.frame.width
    let height = CGFloat(50)

    return CGSize(width: width, height: height)

}

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

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    print(sources[indexPath.item].feed_name)

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: sourceCellId, for: indexPath) as! SourceCell
    cell.preservesSuperviewLayoutMargins = true
    cell.source = sources[indexPath.item]

    return cell

}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    print("selecting")
}}

任何人都知道我在做错了什么?

我希望代码中不仅有一个“愚蠢”的错误,为什么它不起作用,但过去几个小时它一直在吃我的大脑。

2 个答案:

答案 0 :(得分:1)

似乎不合适sourceCollectionView添加为backgroundImage UIImageView中的子视图!从逻辑上讲,图片视图并不代表容器视图(例如UIView UIStackViewUIScrollView),即使代码允许您这样做,它仍然是不合理的;此外,即使向图像视图添加子视图也是正常的(不是),默认情况下图像视图禁用用户交互(默认情况下userInteractionEnabledfalse为图像视图),这就是为什么你甚至无法滚动集合视图,它是禁用的用户交互组件的一部分(子视图)。

viewDidLoad()中,您正在实施:

backgroundImage.addSubview(termsButton)
backgroundImage.addSubview(logo)
backgroundImage.addSubview(sourceCollectionView)

不要这样做,而是将它们添加到视图控制器的主视图中:

view.addSubview(termsButton)
view.addSubview(logo)
view.addSubview(sourceCollectionView)

为了检查问题的原因,至少要对集合视图(view.addSubview(sourceCollectionView))执行此操作。

为了组织视图的层次结构(在另一个上面),您可以同时使用:bringSubview(toFront:)sendSubview(toBack:)。例如,在将集合视图添加到view之后,您可能需要:

view.bringSubview(toFront: sourceCollectionView)

确保集合视图位于所有组件之上。

答案 1 :(得分:0)

我看到你将sourceCollectionView添加到backgroundImage的子视图中。您的backgroundImage是UIImageView,因此UIImageView除了您需要启用它之外没有用户交互。您的代码问题是

backgroundImage.addSubview(sourceCollectionView)

对于我的建议,您应该创建可以与用户交互进行交互的UIView或其他视图。它会正常工作。