以编程方式调整来自 XIB 的自定义 UIView 的大小

2024-01-11

我有以下问题:我创建了一个自定义UIView类及其布局XIB文件。假设我在 XIB 中的自定义视图的大小是 150 x 50。我已启用sizeClasses(瓦尼哈尼)和AutoLayout。在模拟指标中我设置了Size = Freeform, Status Bar = None, all other = Inferred.

我的自定义代码UIView类看起来像这样:

#import "CustomView.h"

@implementation CustomView

#pragma mark - Object lifecycle

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];

    if (self) {
        [self setup];
    }

    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];

    if (self) {
        [self setup];
    }

    return self;
}

#pragma mark - Private & helper methods

- (void)setup {
    if (self.subviews.count == 0) {
        [[NSBundle mainBundle] loadNibNamed:@"CustomView" owner:self options:nil];
        self.bounds = self.view.bounds;
        [self addSubview:self.view];
    }
}

@end

In my UIViewController我想在哪里添加这个自定义UIView,我制作了虚拟 UIView(我在 Interface Builder 中设置了大小),我想在其中添加我的CustomView and 我希望我的CustomView适合我的容器视图的边界.

我正在尝试这样做:

_vCustomView = [[CustomView alloc] init];
_vCustomView.translatesAutoresizingMaskIntoConstraints = NO;
[_vContainer addSubview:_vCustomView];

[_vContainer addConstraint:[NSLayoutConstraint constraintWithItem:_vCustomView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:_vContainer attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0.0]];
[_vContainer addConstraint:[NSLayoutConstraint constraintWithItem:_vCustomView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:_vContainer attribute:NSLayoutAttributeRight multiplier:1.0 constant:0.0]];
[_vContainer addConstraint:[NSLayoutConstraint constraintWithItem:_vCustomView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:_vContainer attribute:NSLayoutAttributeTop multiplier:1.0 constant:0.0]];
[_vContainer addConstraint:[NSLayoutConstraint constraintWithItem:_vCustomView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:_vContainer attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0.0]];

但没有运气。假设我的容器视图是 300 x 100,当我添加自定义视图时UIView to it, 我的自定义视图仍然是 150 x 50.

我尝试在没有容器视图的情况下工作 - 添加我的自定义UIView直接反对我的自我观点UIViewController并设置它的宽度和高度:

  • autoLayout限制条件
  • 通过使用initWithFrame初始化我的自定义时UIView

但再次 - 没有运气。自定义视图始终为 150 x 50。

有人可以向我解释一下我该怎么做吗以编程方式添加我的自定义UIView在制作XIB并使用调整它的大小autoLayout限制条件?

提前谢谢了。

编辑#1:尝试在我的 CustomView 上运行 Andrea 的代码时出现错误

Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) 
(
    "<NSLayoutConstraint:0x17489b760 V:[UIView:0x17418d820(91)]>",
    "<NSLayoutConstraint:0x170c9bf80 V:|-(0)-[CustomView:0x1741da7c0]   (Names: '|':CustomView:0x1741da8b0 )>",
    "<NSLayoutConstraint:0x170c9bfd0 V:[CustomView:0x1741da7c0]-(0)-|   (Names: '|':CustomView:0x1741da8b0 )>",
    "<NSLayoutConstraint:0x170c9be90 V:|-(0)-[CustomView:0x1741da8b0]   (Names: '|':UIView:0x17418d820 )>",
    "<NSLayoutConstraint:0x170c9bee0 CustomView:0x1741da8b0.bottom == UIView:0x17418d820.bottom>",
    "<NSAutoresizingMaskLayoutConstraint:0x170c9dba0 h=--& v=--& CustomView:0x1741da7c0.midY == + 25.0>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x170c9bfd0 V:[CustomView:0x1741da7c0]-(0)-|   (Names: '|':CustomView:0x1741da8b0 )>

编辑#2:它有效!

@Andrea 添加后:

view.translatesAutoresizingMaskIntoConstraints = NO;

in his:

- (void) stretchToSuperView:(UIView*) view;

方法,一切都按照我的预期进行。

感谢@Andrea。


我想主要问题是当您将 xib 添加到内容视图中时,您没有使用自动布局。
在 init 方法中添加子视图后,请调用该方法,传递 xib 的视图:

- (void) stretchToSuperView:(UIView*) view {
    view.translatesAutoresizingMaskIntoConstraints = NO;
    NSDictionary *bindings = NSDictionaryOfVariableBindings(view);
    NSString *formatTemplate = @"%@:|[view]|";
    for (NSString * axis in @[@"H",@"V"]) {
        NSString * format = [NSString stringWithFormat:formatTemplate,axis];
        NSArray * constraints = [NSLayoutConstraint constraintsWithVisualFormat:format options:0 metrics:nil views:bindings];
        [view.superview addConstraints:constraints];
    }

}

[EDIT]
您的设置代码应如下所示:

- (void)setup {
    if (self.subviews.count == 0) {
        [[NSBundle mainBundle] loadNibNamed:@"CustomView" owner:self options:nil];
        self.bounds = self.view.bounds;
        [self addSubview:self.view];
        [self stretchToSuperView:self.view];
    }
}

注意我添加的内部拉伸视图view.translatesAutoresizingMaskIntoConstraints = NO;
[EDIT 2]
我将尝试按要求详细说明我的答案。使用自动布局,当您添加视图而不设置约束时,自动布局会自动将自动调整大小蒙版转换为约束,它们的默认属性是UIViewAutoresizingNone这意味着不自动调整大小。
您的 XIB 视图已无限制地添加到其父视图,并且无法自动调整大小,从而保持其原始大小。由于您希望视图根据您的视图调整大小,因此您有两种选择:

  • 将 xib 视图的自动调整大小蒙版更改为灵活的宽度和高度,但它们需要匹配父级尺寸,否则您将无法获得完整的覆盖
  • 添加一些约束,约束两个视图根据父视图的更改进行相应的更改。您可以在 XIB 视图与其父视图之间实现这样的说法:尾随/前导和顶部/底部之间的间距为 0。就像您在它们的边框上涂了一些胶水一样。为此,您需要将自动翻译调整大小掩码设置为约束为“否”,否则在日志中发布时可能会出现一些冲突。

您稍后要做的是将视图(托管 XIB 视图)的约束添加到其超级视图,但 XIB 与其父级之间没有约束,因此自动布局不知道如何调整 XIB 视图的大小。
视图层次结构中的每个视图都应该有自己的约束。
希望这有助于更好地理解。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

以编程方式调整来自 XIB 的自定义 UIView 的大小 的相关文章

  • Objective C (iphone) 关于发布的问题

    如果我创建一个视图 并将其添加为子视图并将其添加到数组中 是否必须释放它两次 UIView cat UIView alloc initWithFrame someFrame self view addSubview cat self ani
  • 进入后台时 Alamofire 请求卡住?

    我正在使用 Alamofire 调用 Web 服务 该服务需要相当长的时间才能加载 如果应用程序进入后台 当我返回应用程序时 我会被加载程序卡住 我想这是因为调用永远不会向我的完成处理程序返回任何内容 我该如何解决这个问题 您可以使用后台抓
  • iOS 13 检查 CLLocationManager 的临时授权状态

    根据 WWDC 视频 https developer apple com videos play wwdc2019 705 https developer apple com videos play wwdc2019 705 当你要求 Al
  • 如果加载 dylib,垃圾收集工作队列会崩溃

    我们正在将应用程序从 10 6 移植到 10 8 我正在查看我们在应用程序中加载的 dylib 我面临着非常不寻常的崩溃垃圾收集工作队列并附有以下消息 malloc Thread suspend unable to suspend a th
  • UITesting、XCTest 当前 ViewController 类

    简单的问题 我有一个按钮可以执行到下一个视图控制器的操作 我想写 UI XCTest 来告诉我它是否打开了我想要的视图控制器 UI 测试框架无法访问您的应用程序代码 这使得无法对实例进行类断言 你不能够directly告诉屏幕上的控制器的类
  • iPhone SQLite页面缓存不断增长

    I use sqlite数据库用于存储 还有许多数据库事务 我的问题是 sqlite 页面缓存的内存使用量快速增长 在instruments我可以找到这条线 Graph Category Live Bytes Living Transien
  • 如何使用 SwiftUI 获取多个屏幕上的键盘高度并移动按钮

    以下代码获取键盘显示时的键盘高度 并将按钮移动键盘高度 在转换源 ContentView 和转换目标 SecibdContentView 处以相同的方式执行此移动 但按钮在转换目标处不移动 如何使按钮在多个屏幕上移动相同 import Sw
  • 在 UITextView 中获取 HTML

    我在中显示htmlUITextView by self textView setValue b Content b forKey contentToHTMLString 编辑内容后UITextView 我想获取包含 html 的内容 所以我
  • 如何区分 iTunes Connect / Apple TestFlight 上的 STAGE 和 PRODUCTION 版本?

    阶段构建与阶段服务器的对话 阶段服务器与生产服务器尽可能相同 以用于测试目的 生产构建与生产服务器的通信 生产服务器存储真实的关键数据 这些构建本质上是针对同一应用程序的 但是 iTunes Connect 界面将向您显示以下内容 即构建由
  • 如何组合两个 SwiftyJSON 对象

    我有一个 swiftyJSON 对象 例如 location http img http commentCount 0 timestamp 1432460217550 我希望能够向其附加另一个 swiftyJSON 对象 使其看起来像 lo
  • 带约束的嵌套集合视图的意外行为 (Swift 4)

    我的表格视图中有一个单元格 其中包含水平分页集合视图 该集合视图的每个页面内都有一个垂直集合视图 为了避免 滚动滚动 问题 我在垂直集合视图中禁用了垂直滚动 垂直集合视图的单元格计数不是静态的 可以是任意数字 因此 这会产生一个问题 集合视
  • 如何为 Nslocal 通知设置自定义重复间隔......?

    我是 iphone 开发新手 我正在尝试在我的项目中使用 NslocalNotification 我需要每 2 小时或每两天或每两个月等给出提醒 目前我正在使用 NslocalNotification 重复间隔 但它仅适用于使用 Ncale
  • 带有 allowedEditing 的 UIImagePickerController 不允许平移裁剪

    我在这里看到这个问题 UIImagePicker 允许编辑卡在中心 https stackoverflow com questions 12630155 uiimagepicker allowsediting stuck in center
  • 使用 ZBarSDK 时 iPhone 相机失去自动对焦功能

    我正在开发一个应用程序 用户可以选择是否要扫描条形码或拍摄某物的照片 为了拍照 我正在使用UIImagePickerController照常 为了扫描条形码 我使用 ZbarSDK 1 2ZBarReaderViewController 拍
  • cameraOverlayView 防止使用 allowedEditing 进行编辑

    在我的应用程序中 使用以下行在拍摄照片后对其进行编辑 移动和缩放 效果很好 imagePicker setAllowsEditing YES 但如果我还使用cameraOverlayView 则编辑模式将不再起作用 屏幕出现 但平移和捏合手
  • 检查 Objective-C 块类型?

    这主要是出于好奇 我不太确定它的实际用途是什么 但就这样吧 由于块也是 Objective C 对象 是否可以检查它们的类型 也就是说 它是否响应isKindOfClass 消息以及如何使用该消息来处理块 我天真的以为事情大概是这样的 vo
  • cordova插件条码扫描仪打不开扫描

    我的条形码扫描仪插件有问题 我不是天才 我不太了解如何编写网络应用程序 我使用phonegap和cordova 并且尝试制作一个网络应用程序 在单击链接后扫描条形码 我之前已经使用此命令行安装了该插件 cordova plugin add
  • 带有文本字段的 iPhone AlertView

    我有一个UIAlertView with a UITextField在里面 我想输入mail id并提交于UIAlertView s ok按钮 但是UITextField in the UIAlertView没有回复 请帮助我 thankz
  • 领域:结果 和列表

    是否可以转换Results
  • 如何观察UserDefaults的变化?

    我有一个 ObservedObject在我看来 struct HomeView View ObservedObject var station Station var body some View Text self station sta

随机推荐