简体   繁体   中英

Load UIView from XIB

I'm looking for some advice on how to load UIView from XIB file. I tried following 5th solution from this tutorial .

However, the button actions won't work. I setup my project almost exactly as the tutorial, but the IBAction just won't get called at all. I'm not sure if adaptive layout caused this weirdness or not.

Would you be kind enough to take a quick look at what happened in my project? I created a small project just to get the button working and is placed here.

Here is the code snippet:

@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];
}

The editAvatarButtonPressed : method won't get called when the button is clicked.

Thanks in advance. Loc Pham

There are a lot of issues in your code.

  1. You are not assigning any value to __owner.profileHeadingView
  2. Your xib is not correct, you have a top UIView . You need to remove that.

For fixing first issue, you need to do like:

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

For fixing second issue, change your xib design from:

当前

to:

正确

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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