gpt4 book ai didi

swift - 如何存储映射到 UIView 类的自动布局 anchor

转载 作者:行者123 更新时间:2023-11-30 10:53:54 24 4
gpt4 key购买 nike

我目前正在开发一个交互性很强的用户界面。 View 需要根据用户输入移动。我有大约六个 View ,所有子 UI 元素都存储为单独的类。在我的主视图 Controller 中,我想处理这些 View 约束的重置。为了做到这一点,我需要将 NSLayout 约束存储在某处。将它们全部堆放在我的 viewController 中感觉不太对。

我已经经历了相当多的迭代,但每次似乎我都需要手动创建并在父 Viewcontroller 上单独存储所有这些 NSlayoutconstraint 属性。

我不是在寻找一个 UI 扩展,它具有设置约束并将其存储在该类上的属性的功能,以便我可以随意停用或更改它们。

extension UIView {

func anchorFixedHeight(
top: NSLayoutAnchor<NSLayoutYAxisAnchor>,
lead: NSLayoutAnchor<NSLayoutXAxisAnchor>,
trail: NSLayoutAnchor<NSLayoutXAxisAnchor>,
height: CGFloat,
Ypadding: CGFloat,
Xpadding: CGFloat)
{
self.topAnchor.constraint(equalTo: top, constant: Ypadding)
self.heightAnchor.constraint(equalToConstant: height)
self.leadingAnchor.constraint(equalTo: lead, constant: Xpadding)
self.trailingAnchor.constraint(equalTo: trail, constant: -Xpadding)
}

}

但这不会起作用,因为 NSlayouconstrain.activate() 接受约束数组,一旦设置了 anchor ,它就会变成 anchor 约束。

我一直在尝试将它们存储为属性,但 swift 不允许在扩展中存储属性。但我也不想,但我也不想在我的所有 View 中复制所有这些约束属性

最佳答案

你可能需要这样的东西

class CusView:UIView {

var top:NSLayoutConstraint!
var lead:NSLayoutConstraint!
var tra:NSLayoutConstraint!
var heigh:NSLayoutConstraint!

override func didMoveToSuperview() {
super.didMoveToSuperview()

self.translatesAutoresizingMaskIntoConstraints = false
top = self.topAnchor.constraint(equalTo:self.superview!.topAnchor, constant: 12)
heigh = self.heightAnchor.constraint(equalToConstant: 12)
lead = self.leadingAnchor.constraint(equalTo:self.superview!.leadingAnchor, constant: 12)
tra = self.trailingAnchor.constraint(equalTo:self.superview!.trailingAnchor, constant: -12)

NSLayoutConstraint.activate([top,lead,tra,heigh])


}
}

关于swift - 如何存储映射到 UIView 类的自动布局 anchor ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54167920/

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