Rounded Corners only on Top of a UIView

后端 未结 10 1962
别跟我提以往
别跟我提以往 2020-11-29 22:53

Hi i am searching a clean solution without overwriting drawRect or stuff like that to create a UIView with Rounded corners on the Top of the

10条回答
  •  青春惊慌失措
    2020-11-29 23:37

    Modern & Easy solution

    iOS 11+

    Now we have the maskedCorners property on the view's layer & it makes life much easier.

    Just set your desired corner radius and specify which corners should be masked. The best part is that this plays well with borders - the layer border will follow the edge of the layer whether it's rounded or not! Try the following code in a playground (remember to open the live view by pressing command+option+return so you can see what it looks like)

    import UIKit
    import PlaygroundSupport
    
    let wrapperView = UIView(frame: CGRect(x: 0, y: 0, width: 400, height: 160))
    wrapperView.backgroundColor = .lightGray
    
    let roundedCornerView = UIView(frame: CGRect(x: 50, y: 50, width: 300, height: 60))
    roundedCornerView.backgroundColor = .white
    
    wrapperView.addSubview(roundedCornerView)
    
    roundedCornerView.layer.cornerRadius = 10
    roundedCornerView.layer.borderColor = UIColor.red.cgColor
    roundedCornerView.layer.borderWidth = 1
    
    
    // this is the key part - try out different corner combinations to achieve what you need
    roundedCornerView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
    
    
    PlaygroundPage.current.liveView = wrapperView
    

    Here's what it looks like:

提交回复
热议问题