如何在Swift 4中像iOS AppStore那样应用卡片视图的角半径和阴影

时间:2018-06-29 06:21:22

标签: xcode swift3 app-store ios11

我想在今天的iOS应用商店视图之类的集合视图单元中应用“ cornerRadius ”和卡片视图“ 阴影”。

CardView shadow example 1

iOS appstore today view

4 个答案:

答案 0 :(得分:26)

只需向该单元格添加一个子视图并操纵其layer属性。根据自己的喜好调整值。以下代码应提供与在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

答案 1 :(得分:4)

-SwiftUI

struct SimpleRedView: View {
    var body: some View {
        Rectangle()
            .foregroundColor(.red)
            .frame(width: 340, height: 500, alignment: .center)
    }
}

struct ContentView: View {
    var body: some View {
        SimpleRedView()
        .cornerRadius(28)
        .shadow(radius: 16, y: 16)
    }
}

SimpleRedView()仅用于占位符,您可以将其替换为任意类型的View

答案 2 :(得分:1)

创建一个名为“ 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”设置为自定义类即可。简单,易于配置!

答案 3 :(得分:0)

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