【问题标题】:Load UIView from XIB从 XIB 加载 UIView
【发布时间】:2015-04-08 16:47:20
【问题描述】:

我正在寻找一些关于如何从 XIB 文件加载 UIView 的建议。我尝试从 tutorial 遵循第 5 个解决方案。

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

您能不能快速浏览一下我的项目中发生了什么?我创建了一个小项目只是为了让按钮工作并且是placed here.

这里是sn-p的代码:

@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: 方法。

提前致谢。 禄范

【问题讨论】:

    标签: ios objective-c uiview xib


    【解决方案1】:

    你的代码有很多问题。

    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 设计:

    到:

    【讨论】:

    • 感谢 Midhun MP。这解决了我的问题,我已将此标记为正确答案。只是出于好奇,如果您观察作者提供上述教程的示例项目,他所做的正是我所做的,但不知何故,它起作用了。这是他在 Github 上的示例项目,“解耦”是他实现 XIB 的方式,它使 XIB 视图独立且可重用。 github.com/eppz/iOS.Blog.UIView_from_Xib
    • @LocPham:不客气。我正在检查他的项目。
    猜你喜欢
    • 1970-01-01
    • 2017-10-01
    • 1970-01-01
    • 2015-02-03
    • 1970-01-01
    • 1970-01-01
    • 2011-10-11
    • 2017-02-10
    • 1970-01-01
    相关资源
    最近更新 更多