尝试在UIView上转弯时的奇怪行为

时间:2016-12-28 22:45:53

标签: ios swift uiview border

我现在在Swift3中使用UIView在几个小时内挣扎于一种奇怪的行为。我只是想在屏幕内部添加一个UIView,边框是彩色和圆形的。

为了轻松地围绕边框,我使用以下扩展名:

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(),但它没有按预期工作。

  1. 首先,当我在故事板中添加UIView时,不试图添加边框和颜色,我有正确的行为。换一种说法, my UIView is correctly centered inside the screen

  2. 但是,一旦我尝试使用UIView扩展并添加彩色边框, the view is not correctly centered anymore。似乎右边的空间被某种东西裁剪掉了。

  3. 我的猜测是用于绘制边框的蒙版/图层的边界或框架存在问题。但我没有找到任何纠正的方法。

    有什么建议吗?

1 个答案:

答案 0 :(得分:0)

实际上,我在我的UIViewController的viewDidLoad中调用了round方法。然而,正如@ luk2302注意到的,这不适合使用边界,框架等,因为此时视图没有完全加载。

因此,我将调用移到了我的UIViewController的方法viewDidLayoutSubviews中的round方法。这工作正常!