[英]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.我最近添加了一个侧边菜单,它有一个 UITableviewController class 作为菜单。 In this ViewController i added a custom view to the Navbar through this code.在此 ViewController 中,我通过此代码向 Navbar 添加了一个自定义视图。 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.所以它产生如下所示的 output。 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.addSubview(lblTitle)
之后添加下面的代码。
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您正在将newView 添加到 navigationItem的 titleView 而不是将其添加到navigationController 的 navigationBar
self.navigationController?.navigationBar.addSubview(newView)
Try to use auto layout constraint programatically in swift. The link is provided below尝试在 swift 中以编程方式使用自动布局约束。下面提供了链接
Auto Layout in Swift: Writing constraints programmatically Swift 中的自动布局:以编程方式编写约束
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.