【问题标题】:Swift3 center Item in UICollectionViewCellUICollectionViewCell中的Swift3中心项目
【发布时间】:2017-11-29 18:34:18
【问题描述】:

我正在尝试使用以下代码在 UICollectionViewCell 自定义类中居中 UIImageView 但不起作用

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
     return CGSize(width: frame.width/4, height: frame.height)
}

我也在设置单元格的宽度和高度

NSLayoutConstraint.activate([imageView.centerXAnchor.constraint(equalTo: self.centerXAnchor)])
NSLayoutConstraint.activate([imageView.centerYAnchor.constraint(equalTo: self.centerYAnchor)])

我做错了什么?

已编辑 我要归档的完整代码

import UIKit

class MenuBar: UIView,UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{

    lazy var collectionView:UICollectionView = {

        let verticalLayout = UICollectionViewFlowLayout()
        let cv:UICollectionView = UICollectionView(frame: .zero, collectionViewLayout: verticalLayout)
        cv.backgroundColor = UIColor.rgb(red: 230, green: 32, blue: 31)
        cv.delegate = self
        cv.dataSource = self
        return cv
    }()

    let cellId:String = "cellId"

    override init(frame: CGRect) {

        super.init(frame: frame)

        collectionView.register(MenuCell.self, forCellWithReuseIdentifier: cellId)

        addSubview(collectionView)
        addConstraintsWithFormat(format: "H:|[v0]|", views: collectionView)
        addConstraintsWithFormat(format: "V:|[v0]|", views: collectionView)


    }

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

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: frame.width/4, height: frame.height)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }

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

        return cell
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class MenuCell:BaseCell{

    override func setupViews() {
        super.setupViews()

        //backgroundColor = UIColor.yellow

        addSubview(imageView)
        addConstraintsWithFormat(format: "H:|[v0(28)]|", views: imageView)
        addConstraintsWithFormat(format: "V:|[v0(28)]|", views: imageView)

        NSLayoutConstraint.activate([imageView.centerXAnchor.constraint(equalTo: self.centerXAnchor)])
        NSLayoutConstraint.activate([imageView.centerYAnchor.constraint(equalTo: self.centerYAnchor)])
    }

    let imageView:UIImageView = {
        let iv:UIImageView = UIImageView()
        iv.image = UIImage(named: "home")

        return iv
    }()

}

extension UIView{
    func addConstraintsWithFormat(format:String, views:UIView...){
        var viewsDictionary = [String:UIView]()

        for(index, view) in views.enumerated(){
            let key:String = "v\(index)"

            view.translatesAutoresizingMaskIntoConstraints = false
            viewsDictionary[key] = view


        }

        addConstraints(NSLayoutConstraint.constraints(withVisualFormat: format, options: NSLayoutFormatOptions(), metrics: nil, views: viewsDictionary))

    }
}

extension UIColor{
    static func rgb(red:CGFloat,green:CGFloat,blue:CGFloat)->UIColor{
        return UIColor(colorLiteralRed: Float(red/255), green: Float(green/255), blue: Float(blue/255), alpha: 1)
    }
}



class BaseCell: UICollectionViewCell {
    override init(frame: CGRect) {
        super.init(frame: frame)

        setupViews()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func setupViews() {

    }
}

【问题讨论】:

  • 你在哪里使用约束代码?
  • 您需要提供更多信息。你是什​​么意思“不工作”?你的 imageView 不存在吗?是不是尺寸不对?在错误的地方?细胞大小不对?你有错误吗?警告?您在 Cell 类中显示的这段代码在哪里?在 UIView 类中?在你的控制器类中?
  • 为什么不覆盖init(frame: CGRect) 并在那里设置呢?我经常这样做。
  • @DonMag 关于您的评论我编辑了我的问题

标签: ios xcode swift3 uicollectionviewcell


【解决方案1】:

虽然可视化格式语言可以很方便,但它也可以去掉一些“显性”的约束,很容易漏掉一些明显的东西……

MenuCell 类中,添加imageView 作为子视图,然后调用:

    addConstraintsWithFormat(format: "H:|[v0(28)]|", views: imageView)
    addConstraintsWithFormat(format: "V:|[v0(28)]|", views: imageView)

竖线/竖线符号“|”告诉自动布局该视图被“固定”到其父视图的边缘。在您的情况下,您都明确设置了imageView 单元格的大小(在sizeForItemAt中)您说的是“固定imageView 到单元格的两侧。”有些事情不会满足。

如果您只是删除“|”这两行的符号:

    addConstraintsWithFormat(format: "H:[v0(28)]", views: imageView)
    addConstraintsWithFormat(format: "V:[v0(28)]", views: imageView)

您的单元格中应该有一个居中的 28x28 图像视图。

注意:由于您遵循 NSLayoutConstraint.activate() 调用,您也可以以这种方式设置这些约束:

    imageView.translatesAutoresizingMaskIntoConstraints = false

    NSLayoutConstraint.activate([imageView.widthAnchor.constraint(equalToConstant: 28.0)])
    NSLayoutConstraint.activate([imageView.heightAnchor.constraint(equalToConstant: 28.0)])

    NSLayoutConstraint.activate([imageView.centerXAnchor.constraint(equalTo: self.centerXAnchor)])
    NSLayoutConstraint.activate([imageView.centerYAnchor.constraint(equalTo: self.centerYAnchor)])

使用一致的方法可能会降低错过的可能性。

【讨论】:

  • 我是 swift 的新手,但我看到了我的错误。您简短地解释了所有内容,并且效果很好,非常感谢@DonMag
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-30
相关资源
最近更新 更多