菜鸟教程小白 发表于 2022-12-11 18:24:51

ios - 在 UIView 的中心添加 UILabel


                                            <p><p>我的 UICollectionView 创建了一些自定义 UIViews(称为 NumberViews)</p>

<p>每个 NumberView 都有一个属性 <code>var text: UILabel!</code> 这是一个标签,应该在 NumberView 的中间生成。</p>

<p>我做的是:</p>

<ol>
<li><p>我在 UIViewController 中创建 NumberViews</p></li>
<li><p>我在 NumberViews 中创建标签</p></li>
</ol>

<p>(1) 工作得很好,但 (2) 不行。它在 NumberView 之外的某个奇怪的地方创建标签。</p>

<p>对于(2),我在 NumberView 的 init 中这样做:</p>

<pre><code>var text: UILabel!

override init(frame: CGRect) {
    super.init(frame: frame)
    self.text = UILabel(frame: frame)
    self.text.textAlignment = NSTextAlignment.center
    self.text.text = &#34;testing&#34;
    self.addSubview(self.text)
}
</code></pre>

<p>然后发生的事情是这样的:</p>

<pre><code>               ______________    _
            |            |    \
            |   ______   |    |
NumberView --|--&gt; |      ||    |
            |    |______||    |
            |            |    |
      Label --|----&gt; testing |   &gt; ViewController
            |            |    |
            |            |    |
            |            |    |
            |            |    |
            |______________|   _/
</code></pre>

<p>如何将标签移动到 NumberView 的中间?</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>您需要将布局 anchor 添加到您的 numberView 设置它的 center.x 和 center.y 等于标签的。</p>

<p>我现在不在 Mac 上,但您应该可以搜索代码来创建中心布局 anchor 。</p>

<p>快速搜索出现了这个网站:</p>

<p> <a href="http://useyourloaf.com/blog/pain-free-constraints-with-layout-anchors/" rel="noreferrer noopener nofollow">http://useyourloaf.com/blog/pain-free-constraints-with-layout-anchors/</a> </p>

<p>你要创建一个 centerXAnchor 和一个 centerYAnchor</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 在 UIView 的中心添加 UILabel,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/41324557/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/41324557/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 在 UIView 的中心添加 UILabel