简体   繁体   中英

UIView rounded Corner - Swift 2.0?

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.

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:

在此输入图像描述

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM