菜鸟教程小白 发表于 2022-12-13 12:51:58

ios - 以编程方式将由 Interface Builder 安排的自定义 UIViews 替换为 UILabel


                                            <p><p>使用<code>Interface Builder</code>,我构建了一个很长的<code>ScrollView</code>,里面装满了自定义<code>UIViews</code>,常规<code>UIViews</code>, <code>StackViews</code>、<code>UILabels</code>、<code>UIButtons</code> 等</p>

<p>对于某些自定义 UIView,如果它们没有任何数据,那么我想将它们替换为显示“<code>No Data Available</code>”的 UILabel,并且我希望能够设置边距并使该 UILabel 的文本居中。 </p>

<p>鉴于所有 View 都是使用 <code>interface builder 安排的,在我的 <code>ViewController</code> 中以编程方式执行此操作的最佳/最简单方法是什么?</code></p>

<p>提前感谢您的帮助!</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>如果你想确保你不会弄乱你没有控制的控件,你可以通过添加一个带有一些简单约束的 UILabel 来做到这一点。</p>

<p>我设置了一个简单的测试应用程序来展示这种方法的工作原理
<a href="/image/dgmxj.png" rel="noreferrer noopener nofollow"><img src="/image/dgmxj.png" alt="Before image showing some controls"/></a> </p>

<p>这有一个包含一些图像的堆栈 View 、一个 TextView 和一个用于触发示例的按钮。</p>

<p>当您在代码中确定没有要显示的数据并希望显示占位符时,您应该能够将此方法应用于您的 View ,但在我的示例中,我设置了一个 IBOutletCollection,它同时具有堆栈 View 和其中的 TextView ,并在按下按钮时在两个 View 上运行。</p>

<p> <a href="/image/gbn7i.png" rel="noreferrer noopener nofollow"><img src="/image/gbn7i.png" alt="After image showing placeholders instead of controls"/></a> </p>

<p>您需要做的就是提供占位符文本和要替换此方法的 View </p>

<pre><code>/// This method will hide a view and put a placeholder label in that view&#39;s superview, centered in the target view&#39;s frame.
- (void)showPlaceholderText:(NSString *)placeholder forView:(UIView *)view
{
    // Build the placeholder with the same frame as the target view
    UILabel *placeholderLabel = [ initWithFrame:view.frame];
    placeholderLabel.textAlignment = NSTextAlignmentCenter;
    placeholderLabel.text = placeholder;
    placeholderLabel.translatesAutoresizingMaskIntoConstraints = NO;

    // Hide the target view
    view.hidden = YES;

    // Put our placeholder into the superview, overtop the target view
    ;

    // Set up some constraints to ensure the placeholder label stays positioned correctly
    ];
    ];
    ];
    ];
}
</code></pre>

<p>添加到占位符的约束应通过旋转或 View 中的任何其他布局事件保持其正确定位。</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 以编程方式将由 Interface Builder 安排的自定义 UIViews 替换为 UILabel,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/35167859/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/35167859/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 以编程方式将由 Interface Builder 安排的自定义 UIViews 替换为 UILabel