UIView扩展属性

每个视图除了有子视图之外,还可以像Photoshop中更精细的图层来构成,常用的图层有边角属性、阴影色、偏移、透明度、边框粗细等,现在还不能像Photoshop一样直接使用这些属性,需要写代码对其扩展,利用Swift语法的属性扩展Xcode的IBInspectable属性,可以只写一次代码,在属性栏直接设置。
新建UIViewHelper.swift

//  View视图属性扩展
//  UIViewHelper.swift
//  Apple
//
//  Created by 吴学谦 on 2019/9/13.
//  Copyright © 2019 Ryan.com. All rights reserved.
//

import UIKit

extension UIView {
    //圆角
    @IBInspectable//设置属性可检查
    var cornerRadius: CGFloat {
        get {
            return layer.cornerRadius//使view的cornerRadius属性可见
        }
        set {
            layer.cornerRadius = newValue//设置新值
        }
    }
    //阴影圆角
    @IBInspectable
    var shadowRadius: CGFloat {
        get {
            return layer.shadowRadius
        }
        set {
            layer.shadowRadius = newValue
        }
    }
    //阴影透明度
    @IBInspectable
    var shadowOpacity: Float {
        get {
            return layer.shadowOpacity
        }
        set {
            layer.shadowOpacity = newValue
        }
    }
    //阴影颜色,shadowColor类型是cgColor,UIview是UIColor,需要做转换
    @IBInspectable
    var shadowColor: UIColor? {
        get {
            return layer.shadowColor != nil ? UIColor(cgColor: layer.shadowColor!) : nil
        }
        set {
            layer.shadowColor = newValue?.cgColor
        }
    }
    //阴影的偏移
    @IBInspectable
    var shadowOffset: CGSize {
        get {
            return layer.shadowOffset
        }
        set {
            layer.shadowOffset = newValue
        }
    }
}

发布了51 篇原创文章 · 获赞 19 · 访问量 8287

猜你喜欢

转载自blog.csdn.net/WxqHUT/article/details/100799353