iPhone X上自定义UIToolbar按钮距Home Indicator过近的解决咨询
解决自定义UIToolbar按钮与Home Indicator间距过近的问题
我完全懂你的需求——不想移动整个工具栏的位置,只想让按钮和底部Home Indicator保持舒服的间距,就像Mail应用那样对吧?这里有个优雅的解决方案,不用调整toolbar的frame,只需要修改它的内部布局规则:
方法:利用layoutMargins和isLayoutMarginsRelativeArrangement
UIToolbar支持通过布局边距控制内部BarButtonItem的排列,我们只需要给它设置底部边距为当前视图的安全区域高度,就能让按钮自动避开Home Indicator:
let toolbar = UIToolbar() let height = tabBarController?.tabBar.frame.height ?? 0 // 保留你原本的frame设置 toolbar.frame = CGRect(x: 0, y: view.bounds.height - height, width: view.bounds.width, height: height) toolbar.autoresizingMask = [.flexibleWidth, .flexibleTopMargin] // 添加这两行关键代码 toolbar.layoutMargins = UIEdgeInsets(top: 0, left: 0, bottom: view.safeAreaInsets.bottom, right: 0) toolbar.isLayoutMarginsRelativeArrangement = true // 继续配置你的BarButtonItems let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) let yourButton = UIBarButtonItem(title: "按钮", style: .plain, target: self, action: #selector(yourAction)) toolbar.items = [flexibleSpace, yourButton, flexibleSpace] view.addSubview(toolbar)
原理说明
layoutMargins定义了toolbar内部内容与边缘的间距,这里把底部间距设为view.safeAreaInsets.bottom——这个值在iPhone X及以后机型上就是Home Indicator的高度(34pt),旧机型上则为0,完美适配全设备。isLayoutMarginsRelativeArrangement = true会让toolbar内部的BarButtonItem严格遵守我们设置的边距规则,而不是使用默认的紧凑布局。
这样设置后,你的toolbar位置完全不变,但按钮会自动向上调整位置,和Home Indicator保持恰到好处的距离,效果和Mail应用一致。如果你的toolbar是不透明样式,记得把背景色设置成和原tabBar一致的颜色,视觉上会更统一。
内容的提问来源于stack exchange,提问作者nambatee
相关产品推荐
相关产品推荐

