gpt4 book ai didi

ios - 如何将 safeAreaInsets 集成到当前约束扩展

转载 作者:行者123 更新时间:2023-11-28 15:18:36 27 4
gpt4 key购买 nike

我为 View 的约束创建了扩展。您可以在下面找到代码,但是在新发布的 iPhone X 之后我们需要使用 safeAreaInsets 但我不知道如何实现该属性。如果你能帮助我,我会很高兴。

谢谢

    extension UIView {

func anchor (top: NSLayoutYAxisAnchor?, left: NSLayoutXAxisAnchor?, bottom: NSLayoutYAxisAnchor?, right: NSLayoutXAxisAnchor?, paddingTop: CGFloat, paddingLeft: CGFloat, paddingBottom: CGFloat, paddingRight: CGFloat, width: CGFloat, height: CGFloat) {
translatesAutoresizingMaskIntoConstraints = false

if let top = top {
self.topAnchor.constraint(equalTo: top, constant: paddingTop).isActive = true
}
if let left = left {
self.leftAnchor.constraint(equalTo: left, constant: paddingLeft).isActive = true
}
if let right = right {
rightAnchor.constraint(equalTo: right, constant: -paddingRight).isActive = true
}
if let bottom = bottom {
bottomAnchor.constraint(equalTo: bottom, constant: -paddingBottom).isActive = true
}
if height != 0 {
heightAnchor.constraint(equalToConstant: height).isActive = true
}
if width != 0 {
widthAnchor.constraint(equalToConstant: width).isActive = true
}

}

}

最佳答案

我已经重构了您的代码以考虑到插图。尝试以下操作:

import UIKit

extension UIView {

func anchor (top: NSLayoutYAxisAnchor?, left: NSLayoutXAxisAnchor?, bottom: NSLayoutYAxisAnchor?, right: NSLayoutXAxisAnchor?, paddingTop: CGFloat, paddingLeft: CGFloat, paddingBottom: CGFloat, paddingRight: CGFloat, width: CGFloat, height: CGFloat, enableInsets: Bool) {
var topInset = CGFloat(0)
var bottomInset = CGFloat(0)
var rightInset = CGFloat(0)
var leftInset = CGFloat(0)

if #available(iOS 11, *), enableInsets {
let insets = self.safeAreaInsets
topInset = insets.top
bottomInset = insets.bottom
rightInset = insets.right
leftInset = insets.left
}

translatesAutoresizingMaskIntoConstraints = false

if let top = top {
self.topAnchor.constraint(equalTo: top, constant: paddingTop+topInset).isActive = true
}
if let left = left {
self.leftAnchor.constraint(equalTo: left, constant: paddingLeft+leftInset).isActive = true
}
if let right = right {
rightAnchor.constraint(equalTo: right, constant: -paddingRight-rightInset).isActive = true
}
if let bottom = bottom {
bottomAnchor.constraint(equalTo: bottom, constant: -paddingBottom-bottomInset).isActive = true
}
if height != 0 {
heightAnchor.constraint(equalToConstant: height).isActive = true
}
if width != 0 {
widthAnchor.constraint(equalToConstant: width).isActive = true
}

}

}

关于ios - 如何将 safeAreaInsets 集成到当前约束扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46422896/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com