菜鸟教程小白 发表于 2022-12-11 19:53:43

ios - 以编程方式创建约束效果不佳


                                            <p><p>我以编程方式创建了一个带有约束的按钮。但是按钮移动到了错误的位置(右下角)。我做错了什么?</p>

<pre><code>    item = UIButton(type: .custom)
    item.setImage(image, for: .normal)
    item.addTarget(self, action: #selector(PlayController.itemAct(sender:)), for: .touchUpInside)
    item.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(item)

    // Constraints
    item.widthAnchor.constraint(equalToConstant: 30).isActive = true
    item.heightAnchor.constraint(equalToConstant: 30).isActive = true
    item.topAnchor.constraint(equalTo: view.topAnchor, constant: 441).isActive = true
    item.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 123).isActive = true
    item.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 222).isActive = true
    item.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 196).isActive = true
</code></pre>

<p><strong>编辑:</strong></p>

<p>如果你想创建左、右、上、下,你应该为 <code>item.trailingAnchor</code> 和 <code>item.bottomAnchor</code> 设置负值,这对我有用。 </p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>这是我通过约束的一些代码示例,因为有许多不同的方式。这是我最喜欢的一种方式:</p>

<pre><code>containerView.addConstraints([
      NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: containerView, attribute: NSLayoutAttribute.left, multiplier: 1, constant: 0),
      NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: containerView, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0),
      NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: containerView, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: 0),
      NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: containerView, attribute: NSLayoutAttribute.right, multiplier: 1, constant: 0)
      ])
</code></pre>

<p>确保将约束添加到容器 View </p>

<p>还请注意,如果您按照自己的方式进行操作,您只需添加顶部/左侧/右侧/底部或顶部/左侧/宽度/高度。您最多只需要 4 个(通常)</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 以编程方式创建约束效果不佳,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/44621017/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/44621017/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 以编程方式创建约束效果不佳