Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
396 views
in Technique[技术] by (71.8m points)

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

question from:https://stackoverflow.com/questions/65943685/how-to-reduce-the-left-and-right-gaps-in-custom-view-for-navigation-bar-in-ios

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...