从XIB加载UIView

时间:2015-02-09 01:14:56

标签: ios objective-c uiview xib

我正在寻找有关如何从XIB文件加载UIView的建议。我尝试了这个tutorial的第5个解决方案。

但是,按钮操作无效。我几乎完全按照教程设置我的项目,但IBAction根本就不会被调用。我不确定自适应布局是否会导致这种奇怪现象。

您是否愿意快速了解我项目中发生的事情?我创建了一个小项目,只是为了让按钮正常工作,并且placed here.

以下是代码段:

@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:方法不会被调用。

提前致谢。 Pham先生

1 个答案:

答案 0 :(得分:0)

您的代码中存在很多问题。

  1. 您没有为__owner.profileHeadingView
  2. 分配任何值
  3. 你的xib不正确,你有一个顶级UIView。你需要删除它。
  4. 要解决第一个问题,您需要这样做:

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

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

    Current

    为:

    Correct