Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift forEach自动布局约束未出现_Swift_For Loop_Foreach_Autolayout - Fatal编程技术网

Swift forEach自动布局约束未出现

Swift forEach自动布局约束未出现,swift,for-loop,foreach,autolayout,Swift,For Loop,Foreach,Autolayout,我的swifts代码,它使用for循环显示到ImageView。现在代码生成了,但什么也没有出现。我知道我必须将前导锚约束移动到第二个框的0.25。但是我想第一个盒子,也就是盒子1会出现,但是还是什么也没有出现,我不知道为什么 import UIKit class ViewController: UIViewController { var box1 = UIButton();var box2 = UIButton() override func viewDidLoad() {

我的swifts代码,它使用for循环显示到ImageView。现在代码生成了,但什么也没有出现。我知道我必须将前导锚约束移动到第二个框的0.25。但是我想第一个盒子,也就是盒子1会出现,但是还是什么也没有出现,我不知道为什么

import UIKit

class ViewController: UIViewController {
    var box1 = UIButton();var box2 = UIButton()
    override func viewDidLoad() {
        super.viewDidLoad()
        [box1,box2].forEach{
            view.addSubview($0)
            $0.backgroundColor = .red
            $0.translatesAutoresizingMaskIntoConstraints = false
            
            
            $0.heightAnchor.constraint(equalTo: $0.heightAnchor, multiplier: 30).isActive = true
            
            $0.widthAnchor.constraint(equalTo: $0.widthAnchor, multiplier: 30).isActive = true
            $0.leadingAnchor.constraint(equalTo: $0.leadingAnchor ).isActive = true
            $0.topAnchor.constraint(equalTo: $0.topAnchor).isActive = true

        }
    }
    
    
}

您使用的以下代码没有任何意义。您正在尝试将
box1
box2
leadingAnchor
topAnchor
添加到它们自己

$0.leadingAnchor.constraint(equalTo: $0.leadingAnchor ).isActive = true
$0.topAnchor.constraint(equalTo: $0.topAnchor).isActive = true
相反,您需要将约束添加到
self.view

self.view.leadingAnchor.constraint(equalTo: box1.leadingAnchor).isActive = true
box1.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
将上述代码移出
forEach
循环


对于
box2
,您需要使用图像更新您的问题陈述,以澄清
box1
box2
的布局,我不知道您试图将按钮放置在视图中的何处,因为您没有将任何视图引用到要对齐的按钮。试试下面的代码,让我知道它是否适合你

        $0.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 15).isActive = true
        $0.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 15).isActive = true

        $0.heightAnchor.constraint(equalToConstant: 30).isActive = true
        $0.widthAnchor.constraint(equalToConstant: 30).isActive = true

请注意,您试图使用“乘数”而不是“相等常数””设置高度。是的,您可以使用倍增器,但仅当您希望根据父视图或任何其他视图缩放图像时才可以使用倍增器,但在这种情况下,您需要将其设置为常量,因为您正在为其提供浮点值。

您希望按钮如何显示在屏幕上?添加一张示例图片。我在上面的问题中添加了一张我正在寻找的图片。thanksI在我的问题中添加了一张我正在寻找的照片。谢谢上面的代码对你有用吗?屏幕上出现一个按钮了吗@Joebuck按钮出现了,但只出现了一个按钮。您的forEach循环将在视图中进行迭代,并将为您保存在数组中的所有视图提供完全相同的约束。您必须为不同的视图提供不同的约束。这就是为什么只有一个按钮出现,而另一个按钮位于另一个按钮的后面。