如何在Xcode中左对齐导航栏的标题?
我一直在尝试以下操作,以使导航栏的标题保持对齐:
在AppDelegate.swift
文件中:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch.
UINavigationBar.appearance().barTintColor = UIColor.red
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName:
UIColor.white]
return true
}
在TableViewController.swift
文件中:
override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated)
self.navigationController?.navigationBar.topItem?.title = "Home"
}
但我找不到解决问题的方法。我还尝试了以下在此处未显示任何内容的内容:
在AppDelegate.swift
文件中:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch.
UINavigationBar.appearance().barTintColor = UIColor.red
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName:
UIColor.white]
let lbNavTitle = UILabel (frame: CGRect(x: 0, y: 40, width: 320, height: 40))
lbNavTitle.center = CGPoint(x: 160, y: 285)
lbNavTitle.textAlignment = .left
lbNavTitle.text = "Home"
self.navigationItem.titleView = lbNavTitle
在TableViewController.swift
文件中:
override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated)
self.navigationController?.navigationBar.topItem?.title = "Home"
let lbNavTitle = UILabel (frame: CGRect(x: 0, y: 0, width: 320, height: 40))
lbNavTitle.backgroundColor = UIColor.red
lbNavTitle.textColor = UIColor.black
lbNavTitle.numberOfLines = 0
lbNavTitle.center = CGPoint(x: 0, y: 0)
lbNavTitle.textAlignment = .left
lbNavTitle.text = "Home"
let string = NSMutableAttributedString ("Title/nSubTitle")
self.navigationItem.titleView = lbNavTitle
}
回答:
您可以使用navigationItems titleView添加具有左对齐的UILabel,然后使用自动布局设置其框架,如下所示:
let label = UILabel()label.text = "Title Label"
label.textAlignment = .left
self.navigationItem.titleView = label
label.translatesAutoresizingMaskIntoConstraints = false
label.superview?.addConstraint(NSLayoutConstraint(item: label, attribute: .centerX, relatedBy: .equal, toItem: label.superview, attribute: .centerX, multiplier: 1, constant: 0))
label.superview?.addConstraint(NSLayoutConstraint(item: label, attribute: .width, relatedBy: .equal, toItem: label.superview, attribute: .width, multiplier: 1, constant: 0))
label.superview?.addConstraint(NSLayoutConstraint(item: label, attribute: .centerY, relatedBy: .equal, toItem: label.superview, attribute: .centerY, multiplier: 1, constant: 0))
label.superview?.addConstraint(NSLayoutConstraint(item: label, attribute: .height, relatedBy: .equal, toItem: label.superview, attribute: .height, multiplier: 1, constant: 0))
以上是 如何在Xcode中左对齐导航栏的标题? 的全部内容, 来源链接: utcz.com/qa/401424.html