首页 > 解决方案 > 如何减少iOS导航栏自定义视图的左右间隙

问题描述

我最近添加了一个侧边菜单,它有一个 UITableviewController 类作为 Menu 。在这个 ViewController 中,我通过这段代码向导航栏添加了一个自定义视图。但是当我在设备中运行时,我会在视图的左侧和右侧获得额外的空间。如何删除这个?

import UIKit
    
class SettingsTableController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let newView = UIView()
        newView.frame = CGRect(x:UIApplication.shared.statusBarFrame.origin.x,y:UIApplication.shared.statusBarFrame.height, width: view.frame.size.width + 10, height: self.navigationController!.navigationBar.frame.height)
        //#710193
        newView.backgroundColor = UIColor.red
        let lblTitle = UILabel()
        lblTitle.text = "           Animals"
        lblTitle.textColor = UIColor.white
        lblTitle.font = UIFont(name: "HelveticaNeue-Bold", size: 18.0)
        lblTitle.frame = newView.bounds
        newView.addSubview(lblTitle)
        navigationItem.titleView = newView
    }
}

所以它产生如下输出。我想删除通过红色箭头显示的指出的间隙在此处输入图像描述

标签: iosswiftxcodeuitableviewuinavigationbar

解决方案


我在您的代码中更改了一些代码行,它对我来说工作正常

let newView = UIView()
newView.frame = CGRect(x:UIApplication.shared.statusBarFrame.origin.x,y:UIApplication.shared.statusBarFrame.height, width: view.frame.size.width, height: self.navigationController!.navigationBar.frame.height)
//#710193
newView.backgroundColor = UIColor.red
let lblTitle = UILabel()
lblTitle.text = "           Animals"
lblTitle.textColor = UIColor.white
lblTitle.font = UIFont(name: "HelveticaNeue-Bold", size: 18.0)
lblTitle.frame = newView.bounds
newView.addSubview(lblTitle)

您正在将newView 添加到 navigationItem的 titleView而不是将其添加到navigationController 的 navigationBar

  self.navigationController?.navigationBar.addSubview(newView)

推荐阅读