如何获取tabbar底部的屏幕高度,适配不同iOS设备调整自定义按钮位置
自定义TabBar凸起按钮适配刘海屏解决方案
问题出在原有计算逻辑没有考虑带Home刘海设备的底部安全区间距:无刘海设备底部安全区高度为0,TabBar总高度为49pt;带Home条的刘海设备底部安全区高度为34pt,TabBar总高度为49+34=83pt,直接用屏幕高度减固定值会导致刘海屏设备按钮位置向下偏移。
方案1:使用自动布局(推荐,无需手动计算坐标)
直接绑定按钮和TabBar的相对位置,自动适配所有设备和横竖屏场景:
let newButton = UIButton(frame: CGRect(x: 0, y: 0, width: 65, height: 65)) newButton.imageView?.contentMode = .scaleAspectFit newButton.contentHorizontalAlignment = .fill newButton.contentVerticalAlignment = .fill view.addSubview(newButton) // 开启自动布局 newButton.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ newButton.widthAnchor.constraint(equalToConstant: 65), newButton.heightAnchor.constraint(equalToConstant: 65), newButton.centerXAnchor.constraint(equalTo: view.centerXAnchor), // 按钮底部距离TabBar顶部向上偏移10pt newButton.bottomAnchor.constraint(equalTo: tabBar.topAnchor, constant: -10) ])
方案2:手动计算Frame适配
如果必须用Frame布局,需要先获取底部安全区高度再计算坐标,记得在viewDidLayoutSubviews生命周期方法中执行该计算,避免布局变化时位置错误:
let newButton = UIButton(frame: CGRect(x: 0, y: 0, width: 65, height: 65)) newButton.imageView?.contentMode = .scaleAspectFit newButton.contentHorizontalAlignment = .fill newButton.contentVerticalAlignment = .fill var newButtonFrame = newButton.frame // 获取当前视图底部安全区高度 let bottomSafeInset = view.safeAreaInsets.bottom // TabBar总高度 = 标准内容高度49pt + 底部安全区高度 let tabBarTotalHeight: CGFloat = 49 + bottomSafeInset // 计算Y坐标:屏幕总高度 - TabBar总高度 - 按钮高度 - 向上偏移的10pt newButtonFrame.origin.y = view.bounds.height - tabBarTotalHeight - 65 - 10 newButton.frame = newButtonFrame view.addSubview(newButton)
内容的提问来源于stack exchange,提问作者Yuuu
相关产品推荐
相关产品推荐

