skip to Main Content

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 enter image description here.

3

Answers


  1. 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
    
    Login or Signup to reply.
  2. 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)
    
    Login or Signup to reply.
  3. Try to use auto layout constraint programatically in swift. The link is provided below

    Auto Layout in Swift: Writing constraints programmatically

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search