Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIView rounded Corner - Swift 2.0?

Tags:

ios

swift

Ill try to update some projects to Swift 2.0. I´ve got a View, with a rounded corner top left. Everything works fine in Swift < 1.2, but now, there is no rounded corner anymore.

No Warnings, no Errors, just no rounded corner.

This is how it works in Swift < 1.2.

    let maskPath = UIBezierPath(roundedRect: contentView.bounds,byRoundingCorners: .TopLeft, cornerRadii: CGSize(width: 10.0, height: 10.0))
    let maskLayer = CAShapeLayer(layer: maskPath)
    maskLayer.frame = contentView.bounds
    maskLayer.path = maskPath.CGPath
    contentView.layer.mask = maskLayer

Anyone know whats wrong here? Ill dont find any changes in the documentation.

like image 888
derdida Avatar asked Feb 09 '23 18:02

derdida


2 Answers

There's nothing wrong with this piece of code in Swift 2.0–2.1. Are you sure there isn't something else before or after this code snippet, that's affecting your view?

Here's a quick Playground with your code:

enter image description here

like image 157
Erik Tjernlund Avatar answered Feb 19 '23 13:02

Erik Tjernlund


Swift 4.0 - 5.0

You can use a simple class I have created to create a UIView and add rounded corners directly from Storyboard

You can find the class here

import Foundation
import UIKit

@IBDesignable class SwiftRoundView: UIView {

    @IBInspectable fileprivate var borderColor: UIColor = .white { didSet { self.layer.borderColor = self.borderColor.cgColor } }
    @IBInspectable fileprivate var borderWidth: CGFloat = 0.00 { didSet { self.layer.borderWidth = self.borderWidth } }
    @IBInspectable fileprivate var cornerRadius: CGFloat = 0.00 { didSet { self.layer.cornerRadius = self.cornerRadius } }

    init(x: CGFloat = 0.0, y: CGFloat = 0.0, width: CGFloat, height: CGFloat, cornerRadius: CGFloat = 0.0, borderWidth: CGFloat = 0.0, borderColor: UIColor = .white) {
        self.cornerRadius = cornerRadius
        self.borderWidth = borderWidth
        self.borderColor = borderColor

        super.init(frame: CGRect(x: x, y: y, width: width, height: height))

        setupView()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
    }

    required init?(coder aDecoder: NSCoder) {
         super.init(coder: aDecoder)
         setupView()
    }

    fileprivate func setupView() {
        self.layer.cornerRadius = cornerRadius
        self.layer.borderWidth = borderWidth
        self.layer.borderColor = borderColor.cgColor
        self.clipsToBounds = true
    }
}
like image 22
George Leonidas Avatar answered Feb 19 '23 14:02

George Leonidas