ios - 如何在 iOS 中动态地在 UIView 中制作不同的圆角值?

标签 ios swift cocoa-touch uiview

我想为我的 View 制作不同的圆角。我的观点正在动态加载。例如:我有 3 个 View ,想为每个 View 传递不同的角值。

View 1: 左上角:12,左下角:12,右上角:4,右下角:4

View 2: 左上角:4,左下角:4,右上角:12,右下角:12

View 3: 左上角:4,左下角:12,右上角:4,右下角:4

示例代码:

extension UIView{

     enum Corner:Int {
        case bottomRight = 0,
        topRight,
        bottomLeft,
        topLeft
    }

    private func parseCorner(corner: Corner) -> CACornerMask.Element {
        let corners: [CACornerMask.Element] = [.layerMaxXMaxYCorner, .layerMaxXMinYCorner, .layerMinXMaxYCorner, .layerMinXMinYCorner]
        return corners[corner.rawValue]
    }

    private func createMask(corners: [Corner]) -> UInt {
        return corners.reduce(0, { (a, b) -> UInt in
            return a + parseCorner(corner: b).rawValue
        })
    }

    func roundCorners(corners: [Corner], amount: CGFloat) {
        layer.cornerRadius = amount
        let maskedCorners: CACornerMask = CACornerMask(rawValue: createMask(corners: corners))
        if #available(iOS 11.0, *) {
            layer.maskedCorners = maskedCorners
        } else {
            // Fallback on earlier versions
            layer.cornerRadius = 8 // Setting static values for the below versions
        }
    }
}

cardView.roundCorners(corners: [.topRight, .bottomRight], amount: 12).

我想传递角值数组而不是单个值。 期望通过这样的比率:[12,4,12,4]。

最佳答案

如何改用结构。

struct CornerRadius {
    var topLeft: CGFloat = 0
    var topRight: CGFloat = 0
    var bottomLeft: CGFloat = 0
    var bottomRight: CGFloat = 0

    init(_ topLeft: CGFloat, _ topRight: CGFloat, _ bottomLeft: CGFloat, _ bottomRight: CGFloat) {
        self.topLeft = topLeft
        self.topRight = topRight
        self.bottomLeft = bottomLeft
        self.bottomRight = bottomRight
    }
}

let radius = CornerRadius(0, 8, 10, 11)

不知道是不是你想要的答案。

希望对您有所帮助。

关于ios - 如何在 iOS 中动态地在 UIView 中制作不同的圆角值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56487478/

相关文章:

ios - 快速裁剪用相机拍摄的图像

ios - 将 NSManagedObject 复制到 Swift 中的临时 NSManagedObject

ios - 平滑地将渐变应用到 UIImage

swift - SwiftUI Xcode 12 for macOS App 工具栏中的搜索栏

ios - C 数组作为 iOS 中的属性

ios - 作为 NSDates 的所有美国假期列表

ios - 在这个例子中使用内省(introspection)是正确的做法吗?

iOS 比较 GPS 位置

ios - 包含尖括号 <> 的奇数属性声明语法

swift - NSMetadataQuery 不返回任何数据