如何防止显示Sheet时Navigation Title上下移动?
解决iOS拖动Sheet时导航栏标题随之上移的问题
当使用UISheetPresentationController弹出Sheet时,导航栏标题会跟着Sheet上下拖动而移动,无法固定在初始位置,这里提供两种可行的解决办法:
方法一:使用自定义标题视图(推荐)
通过创建自定义的UILabel作为导航栏的标题视图,脱离系统默认的联动逻辑,实现标题固定:
class ViewController: UIViewController { class SheetViewController: UIViewController { override func viewDidLoad() { self.view.backgroundColor = .systemBlue } } override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = .black // 构建自定义标题Label let titleLabel = UILabel() titleLabel.text = "Hello, World!" titleLabel.textColor = .white // 匹配系统默认标题的字体样式 titleLabel.font = UIFont.preferredFont(forTextStyle: .headline) titleLabel.sizeToFit() // 替换系统默认标题为自定义视图 navigationItem.titleView = titleLabel } @IBAction func openSheet(_ sender: Any) { let viewControllerToPresent = SheetViewController() if let sheet = viewControllerToPresent.sheetPresentationController { sheet.detents = [.large()] present(viewControllerToPresent, animated: true, completion: nil) } } }
方法二:关闭导航栏半透明
如果想保留系统默认标题的设置方式,可以通过关闭导航栏的半透明属性,固定导航栏布局:
class ViewController: UIViewController { class SheetViewController: UIViewController { override func viewDidLoad() { self.view.backgroundColor = .systemBlue } } override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = .black self.navigationItem.title = "Hello, World!" let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white] navigationController?.navigationBar.titleTextAttributes = textAttributes // 关闭半透明并设置背景色,固定导航栏布局 navigationController?.navigationBar.isTranslucent = false navigationController?.navigationBar.backgroundColor = .black } @IBAction func openSheet(_ sender: Any) { let viewControllerToPresent = SheetViewController() if let sheet = viewControllerToPresent.sheetPresentationController { sheet.detents = [.large()] present(viewControllerToPresent, animated: true, completion: nil) } } }
原理说明
系统默认的navigationItem.title会绑定导航栏的内部联动逻辑,拖动Sheet时导航栏的细微布局偏移会带动标题移动。自定义标题视图是独立的子视图,不受这套逻辑影响;而关闭半透明后,导航栏的布局会固定,不会随Sheet拖动产生偏移。
内容的提问来源于stack exchange,提问作者Programmer54
相关产品推荐
相关产品推荐

