[英]Round Corners UIView in Swift 4
在 swift 3 中,我可以做這樣的事情來使我的 UIView 角變圓:
import UIKit
@IBDesignable
class DesignableView: UIView {
}
extension UIView {
@IBInspectable
var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
}
}
}
目前,我在可設計時收到“構建失敗”的消息,但我不知道為什么。 我正在 swift 4 和 Xcode 9 上工作。
為什么它在 swift 4 中不起作用?
我試過你的代碼,它在 iOS 11.1 和 Swift 4.0 上運行良好。 (正如您所提到的,它向您顯示了一個錯誤,但沒有向我顯示任何錯誤)
@IBDesignable
class RoundUIView: UIView {
@IBInspectable var borderColor: UIColor = UIColor.white {
didSet {
self.layer.borderColor = borderColor.cgColor
}
}
@IBInspectable var borderWidth: CGFloat = 2.0 {
didSet {
self.layer.borderWidth = borderWidth
}
}
@IBInspectable var cornerRadius: CGFloat = 0.0 {
didSet {
self.layer.cornerRadius = cornerRadius
}
}
}
這是結果
更新:
即使您更新后的代碼也能正常工作。
@IBDesignable
class DesignableView: UIView {
}
extension UIView {
@IBInspectable
var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
}
}
}
這是它的結果:
這個解決方案對我有用,可以在 Swift 5 中獲得四舍五入的 UIView
view.layer.cornerRadius = 10;
view.clipsToBounds = true
public func RoundFrameBackground(_ aView: UIView!, borderWidth: CGFloat!, cornerRadius: CGFloat!, borderColor: UIColor, backgroundColor: UIColor) {
aView.layer.borderWidth = borderWidth ; aView.layer.borderColor = borderColor.cgColor
aView.backgroundColor = backgroundColor ; aView.clipsToBounds = true
aView.layer.cornerRadius = cornerRadius
}
public func RoundFrameOnly(_ aView: UIView!, cornerRadius: CGFloat!) {
aView.clipsToBounds = true
aView.layer.cornerRadius = cornerRadius
}
使用:
RoundFrameBackground(*a view*, borderWidth: 1, cornerRadius: 10, borderColor: UIColor.red, backgroundColor: UIColor.blue)
RoundFrameOnly(*a view*, cornerRadius: 10)
您的代碼在新項目的 Swift 4.0 中似乎運行良好。 但是, 如果您使用 Storyboard 並將其設置為 LaunchScreen,您將無法直接在那里使用自定義類。
在這種情況下,只需取消選中用作啟動屏幕,您應該能夠再次構建。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.