iOS12-Swift5-Xcode10-如何直接在Storyboard的attributes inspector上給view設圓角和陰影

如何直接在Storyboard的attributes inspector上給view設圓角(Rounded Corner)和陰影(Shadow)?

在項目中新建一個Swift文件,用來擴展UIView的功能:bash

import UIKit

extension UIView {
    
    @IBInspectable
    var cornerRadius: CGFloat {
        get {
            return layer.cornerRadius
        }
        set {
            layer.cornerRadius = newValue
        }
    }
    
    @IBInspectable
    var borderWidth: CGFloat {
        get {
            return layer.borderWidth
        }
        set {
            layer.borderWidth = newValue
        }
    }
    
    @IBInspectable
    var borderColor: UIColor? {
        get {
            if let color = layer.borderColor {
                return UIColor(cgColor: color)
            }
            return nil
        }
        set {
            if let color = newValue {
                layer.borderColor = color.cgColor
            } else {
                layer.borderColor = nil
            }
        }
    }
    
    @IBInspectable
    var shadowRadius: CGFloat {
        get {
            return layer.shadowRadius
        }
        set {
            layer.shadowRadius = newValue
        }
    }
    
    @IBInspectable
    var shadowOpacity: Float {
        get {
            return layer.shadowOpacity
        }
        set {
            layer.shadowOpacity = newValue
        }
    }
    
    @IBInspectable
    var shadowOffset: CGSize {
        get {
            return layer.shadowOffset
        }
        set {
            layer.shadowOffset = newValue
        }
    }
    
    @IBInspectable
    var shadowColor: UIColor? {
        get {
            if let color = layer.shadowColor {
                return UIColor(cgColor: color)
            }
            return nil
        }
        set {
            if let color = newValue {
                layer.shadowColor = color.cgColor
            } else {
                layer.shadowColor = nil
            }
        }
    }
}
複製代碼

前面三個是加了圓角屬性 後面四個是加了陰影屬性ide

回到storyboard,點擊任意一個UIView(rootview,button,label等),右邊欄選擇attributes inspector,將會看到:

屏幕快照 2019-05-03 下午6.49.19.png

好了能夠愉快的玩耍了。

 

若是要給imageview加陰影的話,須要把imageview放在一個相同大小的UIView上面,而後給這個UIView加陰影便可:

屏幕快照 2019-05-03 下午7.09.49.png
屏幕快照 2019-05-03 下午7.10.47.png
  注:各個陰影屬性在這篇文章裏有介紹: 如何動態的給view添加陰影shadow

 

廣告時間:小弟的iOS12零基礎視頻教程(每章皆可試聽):

m.study.163.com/provider/48…ui

相關文章
相關標籤/搜索