向 UITabBarController 添加角

Adding Corner To UITabBarController

嗨,我是 iOS 开发新手,遇到了我正在努力克服的挑战。基本上我想将角半径添加到 UITabBarController,但我不知道如何。我检查了 WhosebugYoutube 中的几个资源,人们分享的解决方案要么太复杂而无法理解,要么给出错误,例如 “'UITabBarController' 类型的值没有成员 'layer'。”。顺便说一句,我不使用故事板。

(注意:代码中的注释用于样式目的。由于我无法使它们工作,所以我对它们进行了注释。)

代码:

import UIKit

class TabBarViewController: UIViewController, UITabBarControllerDelegate {
    
    var tabBarCnt: UITabBarController!
    override func viewDidLoad() {
        super.viewDidLoad()
        createTabBar()
        setUpBarStyle()
    }
    func createTabBar(){
        //        viewcontroller.tabBarItem.title = "Dash"
        //        viewcontroller.tabBarItem.image = UIImage.init(named: "imageName")
        //        viewcontroller.tabBarItem.selectedImage= UIImage.init(named: "imageName")
        tabBarCnt = UITabBarController()
        tabBarCnt.tabBar.barStyle = .default
//        let mapVC = MapViewController()
        let homeVC = HomeView()
//        mapVC.tabBarItem.title  = "Map"
        homeVC.title = "Home"
        tabBarCnt.viewControllers = [homeVC]
        
        self.view.addSubview(tabBarCnt.view)
        
    }
    func setUpBarStyle(){
//        would like to add corner radius
        
        
        let layer = CAShapeLayer()
//
//        layer.path = UIBezierPath(roundedRect: CGRect(x: 30, y: self.tabBarCnt.bounds.minY + 5, width: self.tabBar.bounds.width - 60, height: self.tabBar.bounds.height + 10), cornerRadius: (self.tabBar.frame.width/2)).cgPath
//        layer.shadowColor = UIColor.lightGray.cgColor
//        layer.shadowOffset = CGSize(width: 5.0, height: 5.0)
//        layer.shadowRadius = 25.0
//        layer.shadowOpacity = 0.3
//        layer.borderWidth = 1.0
//        layer.opacity = 1.0
//        layer.isHidden = false
//        layer.masksToBounds = false
//        layer.fillColor = UIColor.white.cgColor
//
//        self.tabBarCnt.layer.insertSublayer(layer, at: 0)
//        if let items = self.tabBarCnt.items {
//          items.forEach { item in item.imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: -15, right: 0) }
//        }
//
//        self.tabBarCnt.itemWidth = 30.0
//        self.tabBarCnt.itemPositioning = .centered
    }
}

您可以修改 UITabBarController 中现有的 tabBar。

func setUpBarStyle(){
    // Clipping needs to be enabled, otherwise rounded corners won't show.
    tabBarCnt.tabBar.clipsToBounds = true
    tabBarCnt.tabBar.layer.cornerRadius = 20
    // I guess you want to mask to top left and right corners. If not, change the maskedCorners to what you want.
    tabBarCnt.tabBar.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
}