我想使用带有文字的自定义图标作为启用了preferLargeTitles
的导航栏的标题。自定义标题需要很大并且首先保持居中,然后在滚动时调整大小。它应该是这样的:
带有图标和文字的标题的大导航栏
我尝试使用带有图标和文字的图像,因此我可以创建一个imageView
并将titleView设置为,但这会导致一个小的居中视图覆盖大型导航栏。
我应该怎么做呢?我希望自定义标题的行为与默认的大型导航栏一样,并在向上滚动时调整图像的大小和居中。谢谢!
答案 0 :(得分:0)
试试这个
// Create a navView to add to the navigation bar
let navView = UIView()
// Create the label
let label = UILabel()
label.text = "Assignment"
label.font = UIFont.systemFont(ofSize: 30.0, weight: .bold)
label.sizeToFit()
label.center = navView.center
label.textAlignment = NSTextAlignment.center
// Create the image view
let image = UIImageView()
image.image = UIImage(named: "logo.png")
let imageAspect = image.image!.size.width/image.image!.size.height
image.frame = CGRect(x: label.frame.origin.x-label.frame.size.height*imageAspect - 5, y: label.frame.origin.y, width: label.frame.size.height*imageAspect, height: label.frame.size.height)
image.contentMode = UIViewContentMode.scaleAspectFit
// Add both the label and image view to the navView
navView.addSubview(label)
navView.addSubview(image)
// Set the navigation bar's navigation item's titleView to the navView
self.navigationItem.titleView = navView
self.navigationController?.navigationBar.prefersLargeTitles = true
输出: