美文网首页swift
Swift开发给view设置某几个角为圆角

Swift开发给view设置某几个角为圆角

作者: 一把好刀 | 来源:发表于2019-04-29 11:42 被阅读0次

    在日常开发中我们有时候会遇到View只有部分圆角的需求,这是我们可以让UI给我们切符合需求的图,那么我们能不能用代码实现这一需求呢,答案是肯定的。

    上代码

    给view扩展设置部分角是原角的方法
    extension UIView {
    
        /// 设置多个圆角
        ///
        /// - Parameters:
        ///   - cornerRadii: 圆角幅度
        ///   - roundingCorners: UIRectCorner(rawValue: (UIRectCorner.topRight.rawValue) | (UIRectCorner.bottomRight.rawValue))
         public func filletedCorner(_ cornerRadii:CGSize,_ roundingCorners:UIRectCorner)  {
              let fieldPath = UIBezierPath.init(roundedRect: bounds, byRoundingCorners: roundingCorners, cornerRadii:cornerRadii )
              let fieldLayer = CAShapeLayer()
              fieldLayer.frame =bounds
              fieldLayer.path = fieldPath.cgPath
              self.layer.mask = fieldLayer
        }
    }
    

    调用

    class TextViewController: UIViewController {
        override func viewDidLoad() {
            super.viewDidLoad()
            view.backgroundColor = UIColor.white
    
            let frame = CGRect(x: 0, y: 0, width: 150, height: 150)
            let tempView = UIView(frame: frame)
            tempView.backgroundColor = UIColor.o
            tempView.center  = self.view.center
            view.addSubview(tempView)
            tempView.ViewCornerRadius(CGSize(width: 5, height: 5), 
            UIRectCorner(rawValue: (UIRectCorner.topLeft.rawValue)| 
            (UIRectCorner.topRight.rawValue)))
       }
    }
    

    在iOS11之前想要用代码实现部分圆角在用以上方法,但是iOS11之后就没必要这样麻烦

    class ViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            view.backgroundColor = UIColor.white
            let frame = CGRect(x: 0, y: 0, width: 150, height: 150)
            let tempView = UIView(frame: frame)
            tempView.backgroundColor = UIColor.orange
            tempView.center  = view.center
            view.addSubview(tempView)
    
            if #available(iOS 11.0, *) {
               // iOS11:只需要带用这个系统方法就可以随意设置View的圆角了,是不是很方便,赶快试一下吧
                tempView.layer.cornerRadius = 10
                tempView.layer.maskedCorners = CACornerMask(rawValue: CACornerMask.layerMinXMinYCorner.rawValue | CACornerMask.layerMaxXMinYCorner.rawValue)
            } else {
                tempView.ViewCornerRadius(CGSize(width: 5, height: 5), UIRectCorner(rawValue: (UIRectCorner.topLeft.rawValue)|(UIRectCorner.topRight.rawValue)))
            }
        }
    }
    

    运行效果:

    效果图

    相关文章

      网友评论

        本文标题:Swift开发给view设置某几个角为圆角

        本文链接:https://www.haomeiwen.com/subject/qptynqtx.html