我正在尝试模仿 Apple Music App 使用的 UINavigationBar
的外观(日期显示在大标题上方)。
我知道 Apple Music 应用程序不使用 ios11 的标准 UINavigationBar
但 header View 是 UICollectionView
。
我还想使用 ios11 的标准 UINavigationBar
因为标题文本的大小调整功能。
我可以添加自定义日期标签
来查看大标题 View
的层次结构,我的代码如下所示:
self.title = "Large Title"
navigationController?.navigationBar.prefersLargeTitles = true
guard let navigationBar = navigationController?.navigationBar else { return }
// Create label
let label = UILabel()
label.text = "Small Title"
// Add label to subview hierarchy
for subview in navigationBar.subviews {
let stringFromClass = NSStringFromClass(subview.classForCoder)
if stringFromClass.contains("UINavigationBarLargeTitleView") {
subview.addSubview(label)
}
}
// Add label constraints
label.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
label.leftAnchor.constraint(equalTo: navigationBar.leftAnchor, constant: 16.0),
label.bottomAnchor.constraint(equalTo: navigationBar.bottomAnchor, constant: -50.0),
label.heightAnchor.constraint(equalToConstant: 20.0),
label.widthAnchor.constraint(equalToConstant: 200.0)
])
自定义日期标签
放置正确,但我无法将 UINavigationBar
的高度设置为标签的额外 高度
。
自 ios11 UINavigationBar
使用自动布局,因此设置框架不再像以前的 iOS 版本一样有效。
系统添加的自动布局约束。默认情况下,它的优先级为 1000,因此向标签添加额外的约束不会产生任何影响或导致自动布局冲突。
有什么提示可以在不滚动的情况下在“大标题”上方显示“小标题”吗?
最佳答案
您可以在 UINavigationBarLargeTitleView
中稍微调整一下 UILabel
,例如更改其 Insets 并减小字体大小,这是一个示例:
// Create label
labelSubtitle.text = "Small Title"
labelSubtitle.backgroundColor = UIColor.clear
labelSubtitle.textColor = UIColor.searchBarTextColor(dark: theme)
labelSubtitle.font = UIFont.systemFont(ofSize: 14)
// Add label to subview hierarchy
for subview in self.navigationController!.navigationBar.subviews {
let stringFromClass = NSStringFromClass(subview.classForCoder)
if stringFromClass.contains("UINavigationBarLargeTitleView") {
let largeSubViews = subview.subviews
for sbv in largeSubViews
{
if let lbl = sbv as? UILabel
{
lbl.padding = UIEdgeInsets(top: 4, left: 0, bottom: 0, right: 0)
lbl.setNeedsLayout()
}
}
subview.addSubview(labelSubtitle)
}
}
self.navigationController!.navigationBar.largeTitleTextAttributes = [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 30, weight: .bold)]
labelSubtitle.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
labelSubtitle.leftAnchor.constraint(equalTo: self.navigationController!.navigationBar.leftAnchor, constant: 20.0),
labelSubtitle.bottomAnchor.constraint(equalTo: self.navigationController!.navigationBar.bottomAnchor, constant: -37.0),
labelSubtitle.heightAnchor.constraint(equalToConstant: 20.0),
labelSubtitle.widthAnchor.constraint(equalToConstant: 200.0)
])
要更改插图,我正在使用这篇文章中发布的扩展:Adding space/padding to a UILabel
结果如下:
关于iOS 11 : Height of UINavigationBar for large title (mimic Apple Music App),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49315446/