OGeek|极客世界-中国程序员成长平台

标题: ios - 以编程方式将由 Interface Builder 安排的自定义 UIViews 替换为 UILabel [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 12:51
标题: ios - 以编程方式将由 Interface Builder 安排的自定义 UIViews 替换为 UILabel

使用Interface Builder,我构建了一个很长的ScrollView,里面装满了自定义UIViews,常规UIViewsStackViewsUILabelsUIButtons

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

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

提前感谢您的帮助!



Best Answer-推荐答案


如果你想确保你不会弄乱你没有控制的控件,你可以通过添加一个带有一些简单约束的 UILabel 来做到这一点。

我设置了一个简单的测试应用程序来展示这种方法的工作原理 Before image showing some controls

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

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

After image showing placeholders instead of controls

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

/// This method will hide a view and put a placeholder label in that view's superview, centered in the target view's frame.
- (void)showPlaceholderTextNSString *)placeholder forViewUIView *)view
{
    // Build the placeholder with the same frame as the target view
    UILabel *placeholderLabel = [[UILabel alloc] 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
    [view.superview addSubview:placeholderLabel];

    // Set up some constraints to ensure the placeholder label stays positioned correctly
    [view.superview addConstraint:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:placeholderLabel attribute:NSLayoutAttributeTop multiplier:1.0f constant:0.0f]];
    [view.superview addConstraint:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:placeholderLabel attribute:NSLayoutAttributeRight multiplier:1.0f constant:0.0f]];
    [view.superview addConstraint:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:placeholderLabel attribute:NSLayoutAttributeBottom multiplier:1.0f constant:0.0f]];
    [view.superview addConstraint:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:placeholderLabel attribute:NSLayoutAttributeLeft multiplier:1.0f constant:0.0f]];
}

添加到占位符的约束应通过旋转或 View 中的任何其他布局事件保持其正确定位。

关于ios - 以编程方式将由 Interface Builder 安排的自定义 UIViews 替换为 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35167859/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4