简体   繁体   中英

How to reduce the left and right gaps in custom view for Navigation bar in iOS

I recently added a side menu which is having a UITableviewController class as the Menu. In this ViewController i added a custom view to the Navbar through this code. But when i run in device i get extra space on left and right side of the view. How to remove this?

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

so it produces the output as below. I want to remove the pointed out gaps which is shown through red arrows在此处输入图像描述 .

You are setting frame but also need to autolayout. So after newView.addSubview(lblTitle) add below codes.

newView.translatesAutoresizingMaskIntoConstraints = false
newView.layoutIfNeeded()
newView.sizeToFit()
newView.translatesAutoresizingMaskIntoConstraints = true 
navigationItem.titleView = newView

I have changed some line of code in your code and it is working fine for me

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)

You are adding newView to titleView of navigationItem instead of adding that to navigationBar of navigationController

  self.navigationController?.navigationBar.addSubview(newView)

Try to use auto layout constraint programatically in swift. The link is provided below

Auto Layout in Swift: Writing constraints programmatically

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