ios - UICollectionViewCell 中的 Swift3 中心项目

标签 ios xcode swift3 uicollectionviewcell

我正在尝试使用以下代码将 UIImageView 置于 UICollectionViewCell 自定义类的中心,但不起作用

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() {

    }
}

最佳答案

虽然视觉格式语言可以很方便,但它也可以去除一些约束的“明确性”,并且很容易遗漏一些明显的东西......

在您的 MenuCell 类中,您将 imageView 添加为 subview ,然后调用:

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

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

如果你简单地删除“|”这两行的符号:

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

您的单元格中应该有一个居中的 28x28 ImageView 。

注意:由于您在调用 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)])

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

关于ios - UICollectionViewCell 中的 Swift3 中心项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44767853/

相关文章:

xcode - 无法在 XCode 4.3.2 中打开旧的 .xcodeproj 文件

ios - Xcode中是否有CarPlay模拟器

ios - 将 Dictionary 转换为 Json 以在 Alamofire 中传递参数

ios - 如何为 CNMutableContact 的 `thumbnailImageData` 设置裁剪信息

Swift 2 to 3 迁移核心数据 NSManagedObject 类

ios - 如何判断特定模拟器使用哪个 iOS DeviceSupport 文件夹?

ios - 如何解决webView及其子view的Gesture冲突?

ios - 如何使用 Objective-C 对 TableView 存储的数据进行排序?

ios - 位置管理器不更新位置 ios7

ios - React Native 构建版本 : linker command failed with exit code 1