调整大小时使用 xib 创建的 iOS 布局自定义 View

标签 ios objective-c autolayout custom-controls constraints

我创建了具有两个标签的 MyCustomView。一个在左边,一个在右边对齐并在右边。它有大约 30px 的高度(这并不重要)。我将它连接到 xib 并且它可以工作。在 .xib 中,我将主视图宽度设置为 400px 并为标签设置自动布局约束。

现在是问题。当我使用 UIView 添加到 IB 中的 Controller 并将类设置为 MyCustomView 时,我看到左侧标签但右侧标签不在屏幕上。我设置了正确的约束,但它不起作用。当我尝试通过鼠标在 .xib 中调整 MyCustomView 的大小时并随边缘移动时没问题,但是当我在右列中“手动”设置宽度值时,它的布局不正确(它根本没有改变)。问题出在哪里?我该如何解决这个问题?

@implementation MyCustomView

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

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (void)commonInit
{
    self.backgroundColor = [UIColor clearColor];

    self.view = [[[NSBundle mainBundle] loadNibNamed:@"MyCustomView"
                                               owner:self
                                             options:nil] firstObject];

    [self addSubview:self.view];
    //self.translatesAutoresizingMaskIntoConstraints = NO;
}

- (void)awakeFromNib {
    [super awakeFromNib];

    //[self setNeedsUpdateConstraints];
    //[self setNeedsLayout];
}

@end

正如您在评论中看到的那样,我尝试了一些方法但没有任何帮助。

最佳答案

  1. 新建文件 --> iOS(源代码)-- Cocoa Touch --> 下一步 New File

  2. 输入姓名 MyCustomView

  3. 在MyCustomView.m中添加代码

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        //self.view.backgroundColor = [UIColor redColor];
        self.preferredContentSize = CGSizeMake(30.0, 400.0);
    }
    return self;
}

关于调整大小时使用 xib 创建的 iOS 布局自定义 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28085311/

相关文章:

iOS/苹果 watch : iPhone app network request callback blocks not triggered when app is in background

ios - 如何使用AVPlayer中的缓存播放ts文件?

IOS devicesWithMediaType 弃用

cocoa - 使用 NSView.layoutSubtreeIfNeeded() 动画自动布局约束在 macOS High Sierra 上不起作用

ios App Store 显示对钱包的支持,即使钱包已在应用程序功能中被禁用

ios - SWIFT - 'double' 不可转换为 'string'

ios - 使用 SDK 3.3.0.GA 运行 iOS 测试模块时缺少 Titanium 运行命令

iphone - 如何知道 UITextView 是否有焦点

iphone - 旋转固定位置的 UILabel

ios - 自动布局中按钮之间的等宽和等间距