0

我有一个简单的 UICollectionViewCell,它是全宽的,我正在使用 SnapKit 来布局它的子视图。我将 SnapKit 用于我的其他视图,它运行良好,但不在 collectionViewCell 中。这是我想要实现的布局: collectionViewCell layout

collectionViewCell 的代码是:

lazy var imageView: UIImageView = {
    let img = UIImageView(frame: .zero)
    img.contentMode = UIViewContentMode.scaleAspectFit
    img.backgroundColor = UIColor.lightGray
    return img
}()

override init(frame: CGRect) {
    super.init(frame: frame)

    let imageWidth = CGFloat(frame.width * 0.80)
    let imageHeight = CGFloat(imageWidth/1.77)
    backgroundColor = UIColor.darkGray

    imageView.frame.size.width = imageWidth
    imageView.frame.size.height = imageHeight
    contentView.addSubview(imageView)

    imageView.snp.makeConstraints { (make) in
        make.top.equalTo(20)
        //make.right.equalTo(-20)
        //make.right.equalTo(contentView).offset(-20)
        //make.right.equalTo(contentView.snp.right).offset(-20)
        //make.right.equalTo(contentView.snp.rightMargin).offset(-20)
        //make.right.equalToSuperview().offset(-20)
    }
}

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

在不应用任何约束的情况下,imageView 会显示在单元格的左上方,但应用任何约束会使图像消失。在调试视图中检查 collectionViewCell 会显示 imageView 和约束,但“UIImageView 的大小和水平位置不明确”。

我还尝试设置 contentView.translatesAutoresizingMaskIntoConstraints = false 等,但结果相同。

我正在使用所有代码,没有故事板 UI 或布局。

谢谢你的帮助!

4

2 回答 2

0

您不能同时使用自动布局(SnapKit)和手动布局(设置框架)。通常,使用自动布局会导致手动布局失败。但是,您在 snp 闭包中的约束代码并不完整。无论是使用自动布局还是手动布局,最终视图都应该得到位置和大小。

所以,你可以这样尝试:

imageView.snp.makeConstraints { make in
   // set size
   make.size.equalTo(CGSize(width: imageWidth, height: imageHeight))
   // set position
   make.top.equalTo(20)
   make.centerX.equalTo(contentView)
}
于 2017-06-01T02:00:50.363 回答
-1

我对 SnapKit 了解不多,但看起来你缺少一个约束。您需要高度、宽度、x 和 y。适用于 IOS 9 约束。

let imageView: UIImageView = {
        let view = UIImageView()
        view.translatesAutoresizingMaskIntoConstraints = false
        view.contentMode = .scaleAspectFit
        view.backgroundColor = .lightGray
        return view
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
    }

    func setupViews() {
        self.addSubview(imageView)

        imageView.topAnchor.constraint(equalTo: self.topAnchor, constant: 10).isActive = true
        imageView.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -10).isActive = true
        imageView.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 2/3, constant: -10).isActive = true
        imageView.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 1/2, constant: -10).isActive = true
    }
于 2017-05-31T23:55:11.963 回答