为了轻松地围绕边框,我使用以下扩展名:
extension UIView {
/**
Rounds the given set of corners to the specified radius
- parameter corners: Corners to round
- parameter radius: Radius to round to
*/
func round(corners: UIRectCorner, radius: CGFloat) {
_round(corners: corners, radius: radius)
}
/**
Rounds the given set of corners to the specified radius with a border
- parameter corners: Corners to round
- parameter radius: Radius to round to
- parameter borderColor: The border color
- parameter borderWidth: The border width
*/
func round(corners: UIRectCorner, radius: CGFloat, borderColor: UIColor, borderWidth: CGFloat) {
let mask = _round(corners: corners, radius: radius)
addBorder(mask: mask, borderColor: borderColor, borderWidth: borderWidth)
}
/**
Fully rounds an autolayout view (e.g. one with no known frame) with the given diameter and border
- parameter diameter: The view's diameter
- parameter borderColor: The border color
- parameter borderWidth: The border width
*/
func fullyRound(diameter: CGFloat, borderColor: UIColor, borderWidth: CGFloat) {
layer.masksToBounds = true
layer.cornerRadius = diameter / 2
layer.borderWidth = borderWidth
layer.borderColor = borderColor.cgColor;
}
}
private extension UIView {
@discardableResult func _round(corners: UIRectCorner, radius: CGFloat) -> CAShapeLayer {
let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.cgPath
self.layer.mask = mask
return mask
}
func addBorder(mask: CAShapeLayer, borderColor: UIColor, borderWidth: CGFloat) {
let borderLayer = CAShapeLayer()
borderLayer.path = mask.path
borderLayer.fillColor = UIColor.clear.cgColor
borderLayer.strokeColor = borderColor.cgColor
borderLayer.lineWidth = borderWidth
borderLayer.frame = bounds
layer.addSublayer(borderLayer)
}
}
class GameViewController: UIViewController {
@IBOutlet weak var cardView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
cardView.round(corners: UIRectCorner.allCorners, radius: 5.0, borderColor: DesignHelper.defaultColor, borderWidth: 1)
}
}
我只是使用正确的参数调用myView.round(),但它没有按预期工作。
首先,当我在故事板中添加UIView时,不试图添加边框和颜色,我有正确的行为。换一种说法, my UIView is correctly centered inside the screen
但是,一旦我尝试使用UIView扩展并添加彩色边框, the view is not correctly centered anymore。似乎右边的空间被某种东西裁剪掉了。
我的猜测是用于绘制边框的蒙版/图层的边界或框架存在问题。但我没有找到任何纠正的方法。
有什么建议吗?
答案 0 :(得分:0)
实际上,我在我的UIViewController的viewDidLoad中调用了round方法。然而,正如@ luk2302注意到的,这不适合使用边界,框架等,因为此时视图没有完全加载。
因此,我将调用移到了我的UIViewController的方法viewDidLayoutSubviews中的round方法。这工作正常!