如何在swift 4中应用卡片视图cornerRadius&shadow,如iOS appstore

Rah*_*Roy 12 xcode app-store swift3 ios11

我想在我的集合视图单元格中应用" cornerRadius "和卡片视图" shadow ",就像今天的iOS appstore View一样.

CardView阴影示例1

iOS appstore今天查看

oyv*_*uge 45

只需将子视图添加到单元格并操纵它的图层属性即可.根据自己的喜好调整值.以下代码应该在App Store中显示类似的结果:

    // The subview inside the collection view cell
    myView.layer.cornerRadius = 20.0
    myView.layer.shadowColor = UIColor.gray.cgColor
    myView.layer.shadowOffset = CGSize(width: 0.0, height: 0.0)
    myView.layer.shadowRadius = 12.0
    myView.layer.shadowOpacity = 0.7
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Zah*_*sal 6

创建一个名为“ CardView”的新UIView子类,如下所示:

import Foundation
import UIKit

@IBDesignable
class CardView: UIView {

    @IBInspectable var cornerRadius: CGFloat {
        get {
            return layer.cornerRadius
        }
        set {
            layer.cornerRadius = newValue
            layer.shadowRadius = newValue
            layer.masksToBounds = false
        }
    }

    @IBInspectable var shadowOpacity: Float {
        get {
            return layer.shadowOpacity
        }
        set {
            layer.shadowOpacity = newValue
            layer.shadowColor = UIColor.darkGray.cgColor
        }
    }

    @IBInspectable var shadowOffset: CGSize {
        get {
            return layer.shadowOffset
        }
        set {
            layer.shadowOffset = newValue
            layer.shadowColor = UIColor.black.cgColor
            layer.masksToBounds = false
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

然后只需从XCode Interface Builder将“ CardView”设置为自定义类即可。它简单易配置!