【问题标题】:How to load custom UIView from xib file into a UIView in UIViewController?如何将自定义 UIView 从 xib 文件加载到 UIViewController 中的 UIView?
【发布时间】:2016-10-31 16:40:17
【问题描述】:

我创建了一个 xib 文件。

下面是代码:

#import "LoginView.h"
@implementation LoginView

-(id)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
    // Initialization code
    [self setup];
}
return self;
}

-(void) setup{
[[NSBundle mainBundle] loadNibNamed:@"LoginView" owner:self options:nil];

self.bounds = self.loginView.bounds;

[self addSubview:self.loginView];
}

现在我创建了一个视图控制器并向它添加了一个 UIView。在 viewWillAppear 中,我试图将 xib 文件加载到我的视图控制器中定义的 UIView 中。

-(void)viewWillAppear:(BOOL)animated{
self.containerView.layer.borderColor = [UIColor blackColor].CGColor;
self.containerView.layer.borderWidth = 2.0f;
LoginView *loginView = [[LoginView alloc] initWithFrame:CGRectMake(self.containerView.frame.origin.x,self.containerView.frame.origin.y, self.containerView.frame.size.width, self.containerView.frame.size.height)];
[self.containerView addSubview:loginView];
}

但是,xib 文件超出了我命名为 containerView 的已定义 UIView。我已将 containerView 链接到 ViewController 中的 UIView。

@property(nonatomic, weak) IBOutlet UIView *containerView;

谁能帮助我为什么会得到这个输出?我需要在 ViewController 的 containerView 中获取自定义 uiview。就像文本字段和按钮应该在黑色边框内一样。

【问题讨论】:

    标签: ios objective-c uiview uiviewcontroller storyboard


    【解决方案1】:

    当您在容器视图上添加视图时,x 和 y 应该是 0,0

    你需要替换这个:

    LoginView *loginView = [[LoginView alloc] initWithFrame:CGRectMake(self.containerView.frame.origin.x,self.containerView.frame.origin.y, self.containerView.frame.size.width, self.containerView.frame.size.height)];
    

    通过这个:

    LoginView *loginView = [[LoginView alloc] initWithFrame:CGRectMake(0,0, self.containerView.frame.size.width, self.containerView.frame.size.height)];
    

    希望对您有所帮助!

    【讨论】:

    • 现在,自定义视图位于定义的容器视图中。但它不适合视图。如何完美地将自定义视图放入容器视图中>
    • 可以给个截图吗,现在是怎么显示的。
    • 容器视图正在扩展,容器视图和登录视图的宽高不一样吗?你用过自动布局吗?
    • 是的,但是自定义视图不完全适合容器视图。
    猜你喜欢
    • 2017-10-01
    • 2015-02-03
    • 2020-05-16
    • 1970-01-01
    • 1970-01-01
    • 2016-06-10
    • 2011-06-15
    • 1970-01-01
    • 2019-11-26
    相关资源
    最近更新 更多