首页 > 解决方案 > 设置视图的圆角和阴影

问题描述

我需要围绕视图的左下角和右下角,并根据我在互联网上找到的内容,我在 UIview 扩展中创建了这个函数:

func setRoundedCorner(withRadius radius: CGSize, forCorners corners: UIRectCorner ) {

    let viewShape = CAShapeLayer()
    viewShape.bounds = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: self.bounds.width, height: self.bounds.height)
    viewShape.position = self.center
    viewShape.path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: radius).cgPath
    self.layer.mask = viewShape

}

现在,我遇到了这个解决方案的两个问题;尽管它非常适合静态视图,但我的视图以编程方式更改其高度,导致视图被截断;我找到了解决该问题的方法,每次都回忆该setRoundedCorner方法,但在我看来这很不舒服;有没有其他方法可以解决这个问题?另一个我更难解决的问题是影子集。我通常使用这种方法:

func setShadow(height: CGFloat, width: CGFloat, opacity: Float, radius: CGFloat) {
    self.layer.shadowPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: self.layer.cornerRadius).cgPath
    self.layer.shadowColor = UIColor.black.cgColor
    self.layer.shadowOpacity = opacity
    self.layer.shadowOffset = CGSize(width: width, height: height)
    self.layer.cornerRadius = radius
    self.layer.masksToBounds = false
}

相反,当视图本身应该有阴影时,视图会以这种方式显示:

在此处输入图像描述

但在这种情况下似乎根本不显示任何阴影。谁能给我一些建议?

标签: iosswiftshadowrounded-corners

解决方案


在这里,我与您分享我的类别,用于添加角半径(使用 BezierPath),同时支持添加阴影。

import UIKit

/// A category for all views.
extension UIView {
    /// Setups the layer of a view.
    public func setupLayer(
        cornerRadius: CGFloat = 22,
        borderWidth: CGFloat = 0,
        borderColor: UIColor = .clear,
        shadowOffSet: CGSize = CGSize(width: 0, height: 1),
        shadowColor: UIColor = UIColor(red:0, green:0, blue:0, alpha:0.15),
        shadowOpacity: Float = 1,
        shadowRadius: CGFloat = 2,
        shouldClipToBounds: Bool = false
        ) {

        self.layer.cornerRadius     = cornerRadius
        self.layer.borderWidth      = borderWidth
        self.layer.borderColor      = borderColor.cgColor
        self.layer.shadowOffset     = shadowOffSet
        self.layer.shadowColor      = shadowColor.cgColor
        self.layer.shadowOpacity    = shadowOpacity
        self.layer.shadowRadius     = shadowRadius
        self.clipsToBounds = shouldClipToBounds
    }

    /// Round the corner radius with bezier path.
    func roundCorners(_ corners: UIRectCorner, radius: CGFloat) {
        let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        let mask = CAShapeLayer()
        mask.path = path.cgPath
        self.layer.mask = mask
    }
}

随意编辑这一切。现在,让我们谈谈你的问题。顺便说一句,这段代码,我在我的生产项目中使用它。有时你需要在你的viewDidLayoutSubviews, viewWillLayoutSubviews. 如果您使用的是 aUIView或类似类的子类,那么您可以在它们的函数中UITableViewCell添加圆角代码。draw

override func draw(_ rect: CGRect) {
        super.draw(rect)
    // Round corners here...
}

在此处输入图像描述

最后,为了设置层,我通常在我的控件的惰性初始化声明中调用它(例如按钮、文本字段...)。了解使用 bezierPath 和简单地 layer.cornerRadius 添加角的区别。:)

我希望这有帮助!


推荐阅读