2017-05-31 68 views
0

我有一个简单的UICollectionViewCell,它是全角,我使用SnapKit来布局它的子视图。我为我的其他视图使用SnapKit,它工作的很好,但不在collectionViewCell中。这是我想达到的布局: collectionViewCell layoutUICollectionViewCell与SnapKit的布局

的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 =其他事情,但结果相同。

我使用的所有代码和故事板UI或布局。

感谢您的帮助!

回答

0

我对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 
    } 
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) 
} 
+0

这工作 - THKS。对于x位置,我必须将代码更新为 - make.centerX.equalTo(contentView.snp.centerX)。虽然我的布局,我想图像拥抱单元格的右侧,所以我用make.right.equalTo(contentView.snp.rightMargin)来代替。 – Dennish