如何在swift 4中应用卡片视图角度半径和阴影,如iOS appstore

问题描述 投票:6回答:3

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

CardView shadow example 1

iOS appstore today view

xcode swift3 app-store ios11
3个回答
36
投票

只需将子视图添加到单元格并操纵它的图层属性即可。根据自己的喜好调整值。以下代码应该在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

enter image description here


4
投票

创建一个名为“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
        }
    }

}

然后从XCode Interface Builder中为您的视图设置“CardView”作为自定义类。它简单易用!


0
投票

要添加到@oyvindhauge的好答案 - 确保myView内的任何子视图都不会延伸到边缘。例如,我的卡片视图包含填充卡片的表格视图 - 因此有必要设置tableView.layer.cornerRadius = 20.0。这适用于填充卡的任何子视图。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.