gpt4 book ai didi

Swift:以编程方式将自动布局约束从一个 View 复制到另一个 View

转载 作者:搜寻专家 更新时间:2023-10-30 21:57:35 29 4
gpt4 key购买 nike

我有一个 UIButton,我在 Storyboard中设置了自动布局约束。我还有一个 UIView,我在 UIViewControllerviewDidLoad 方法中启动它。我使此 View 具有(几乎)所有与 UIButton 相同的属性,但是当我在模拟器中运行它时,它不会“粘”在按钮上。这是我所拥有的:

class ViewController: UIViewController {

@IBOutlet weak var someButton: UIButton!

func viewDidLoad() {
super.viewDidLoad()

let someView = UIView()
someView.backgroundColor = UIColor.greenColor()
someView.frame = someButton.bounds
someView.frame.origin = someButton.frame.origin
someView.autoresizingMask = someButton.autoresizingMask
someView.autoresizesSubviews = true
someView.layer.cornerRadius = someButton.layer.cornerRadius
someView.clipsToBounds = true
someView.userInteractionEnabled = false
view.insertSubview(someView, belowSubview: someButton)
}

}

我想我缺少 someView.auto 布局约束?

编辑:我认为访问 UIButton 的约束会起作用,但它们似乎是一个空数组。 Storyboard约束是否被隐藏?

someView.addConstraints(someButton.constraints)

谢谢。

最佳答案

以这种方式复制约束失败,因为:

  • Storyboard中的约束被添加到父 View 而不是按钮本身
  • 您尝试复制的约束引用的是按钮而不是您的新 View

与其复制约束,不如保持简单并创建新约束并引用按钮:

    let someView = UIView()
someView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(someView)

view.addConstraints([
NSLayoutConstraint(item: someView, attribute: .Leading, relatedBy: .Equal, toItem: someButton, attribute: .Leading, multiplier: 1, constant: 0),
NSLayoutConstraint(item: someView, attribute: .Trailing, relatedBy: .Equal, toItem: someButton, attribute: .Trailing, multiplier: 1, constant: 0),
NSLayoutConstraint(item: someView, attribute: .Top, relatedBy: .Equal, toItem: someButton, attribute: .Top, multiplier: 1, constant: 0),
NSLayoutConstraint(item: someView, attribute: .Bottom, relatedBy: .Equal, toItem: someButton, attribute: .Bottom, multiplier: 1, constant: 0)
])

关于Swift:以编程方式将自动布局约束从一个 View 复制到另一个 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35800870/

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