卡样式集合

时间:2018-08-22 00:42:01

标签: ios swift uikit

所以我正在尝试构建类似于本文中看到的那样的卡片样式collectionViewCell

https://medium.com/@phillfarrugia/building-a-tinder-esque-card-interface-5afa63c6d3db

经过大量搜索,我发现了一些代码,这些代码似乎模拟了集合视图单元格的外观。

cell.contentView.layer.cornerRadius = 8.0
cell.contentView.layer.borderWidth = 1.0
cell.contentView.layer.borderColor = UIColor.clear.cgColor
cell.contentView.layer.masksToBounds = true;

cell.layer.shadowColor = UIColor.lightGray.cgColor
cell.layer.shadowOffset = CGSize(width:0,height: 2.0)
cell.layer.shadowRadius = 2.0
cell.layer.shadowOpacity = 1.0
cell.layer.masksToBounds = false
cell.layer.shadowPath = UIBezierPath(roundedRect:cell.bounds, cornerRadius:cell.contentView.layer.cornerRadius).cgPath

但是,当我运行代码时,我的单元格看起来像这样

enter image description here

一点都不像卡片样式的UI。我还可以看到背后的阴影,所以我知道有些冲突。我的代码存储单元并不复杂,但是我一直在对其进行更改,并且没有看到任何真正的变化可以帮助我。

import UIKit

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

    public var backgroundImageView: UIImageView = {
        let firstImage = UIImageView()
        firstImage.clipsToBounds = true
        firstImage.translatesAutoresizingMaskIntoConstraints = false
        firstImage.contentMode = .scaleToFill
        firstImage.image = UIImage(named: "scott_7")
        firstImage.layer.cornerRadius = 20
        return firstImage
    }()

    @objc func setupViews(){
        setCellShadow()
        addSubview(backgroundImageView)
        backgroundImageView.snp.makeConstraints { (make) in
            make.edges.equalTo(self)
        }
    }

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

1 个答案:

答案 0 :(得分:0)

阴影是绘制在视图外部的,即使您将masksToBounds设置为false,我也认为阴影被单元格裁剪了。

我这样做的方法是使单元格和contentView背景清晰,然后添加我自己的另一个contentView,并在各个面上插入所需大小的阴影。

然后我将其他子视图添加到该单元格中。

cell.backgroundColor = .clear
cell.contentView.backgroundColor = .clear

let shadowContentView = UIView( frame:cell.contentView.bounds.insetBy( dx:4.0, dy:4.0)
shadowContentView.layer.shadowColor = UIColor.lightGray.cgColor
shadowContentView.layer.shadowOffset = CGSize(width:0.0, height: 2.0)
shadowContentView.layer.shadowRadius = 2.0
shadowContentView.layer.shadowOpacity = 1.0
shadowContentView.layer.cornerRadius = 20.0
shadowContentView.layer.masksToBounds = false
shadowContentView.backgroundColor = .white 

let firstImageView = UIImageView()
firstImageView.layer.cornerRadius = 20.0
firstImageView .layer.masksToBounds = false
shadowContentView.addSubView( firstImageView)