繁体   English   中英

从XIB加载UIView

[英]Load UIView from XIB

我正在寻找有关如何从XIB文件加载UIView的一些建议。 我尝试了本教程中的第5个解决方案。

但是,按钮操作将不起作用。 我几乎完全按照教程设置了我的项目,但是IBAction根本不会被调用。 我不确定自适应布局是否会引起这种怪异。

您足够友善地快速看一下我的项目中发生了什么吗? 我创建了一个小项目来使按钮正常工作,并将其放置在此处。

这是代码片段:

@interface ProfileHeadingViewOwner : NSObject
@property (nonatomic, weak) IBOutlet ProfileHeadingView *profileHeadingView;
@end

@implementation ProfileHeadingViewOwner
@end

static ProfileHeadingViewOwner* __owner = nil;

@interface ProfileHeadingView ()
@property (nonatomic, weak) IBOutlet UILabel *profileName;
@property (nonatomic, weak) UIViewController <ProfileHeadingViewDelegate> *delegateViewController;
@end

@implementation ProfileHeadingView

+(void)presentInViewController:(UIViewController<ProfileHeadingViewDelegate>*) viewController
{
    // Instantiating encapsulated here.
    //ProfileHeadingViewOwner *owner = [ProfileHeadingViewOwner new];
    __owner = [ProfileHeadingViewOwner new];
    [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self) owner:__owner options:nil];

    // Pass in a reference of the viewController.
    __owner.profileHeadingView.delegateViewController = viewController;


    // Add (thus retain).
    [viewController.view addSubview:__owner.profileHeadingView];
}

+(void)setProfileName:(NSString*)name {
    __owner.profileHeadingView.profileName.text = name;
}


-(IBAction)editAvatarButtonPressed:(UIButton *)sender {

    ////// THIS METHOD WON'T GET CALLED. WHY? ///////

    [self.delegateViewController uploadProfileAvatar:self];
}

单击按钮时不会调用editAvatarButtonPressed :方法。

提前致谢。 Loc Pham

您的代码中有很多问题。

  1. 您没有为__owner.profileHeadingView分配任何值
  2. 您的xib不正确,您有一个顶部UIView 您需要删除它。

要解决第一个问题,您需要执行以下操作:

__owner = [ProfileHeadingViewOwner new];
__owner.profileHeadingView = (ProfileHeadingView *)[[[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self) owner:__owner options:nil] objectAtIndex:0];
__owner.profileHeadingView.delegateViewController = viewController;

要解决第二个问题,请从以下位置更改您的xib设计:

当前

至:

正确

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM