【问题标题】:iPhone: View that is a Property Fails to Appear after Adding a @synthesize Directive for the PropertyiPhone:为属性添加@synthesize 指令后无法显示作为属性的视图
【发布时间】:2023-04-04 15:45:01
【问题描述】:

我有一个带有标签栏控制器的 mainwindow.xib。第一个标签栏有一个视图,从“View1.xib”加载。在我的 View1.xib 中,我将 UI 元素拖到上面。它在 .h 中有这个:

#import <UIKit/UIKit.h>
@class View1Controller;


@interface View1Controller : UIViewController {
    IBOutlet UIView *view;
    IBOutlet UIButton *startButton;
}

@property (retain, nonatomic) UIView *view;
@property (retain, nonatomic) UIButton *startButton;


-(IBAction)startClock:(id)sender;

@end

在 .m 文件中,我什么也不做。它会正常运行。我可以看到视图及其按钮。但是在我添加之后:

@synthesize view, startButton;

当我加载应用程序时,它显示一个没有按钮但没有产生错误的空白视图。发生了什么?

【问题讨论】:

    标签: objective-c iphone properties uiviewcontroller xib


    【解决方案1】:

    问题是您将viewstartButton 变量声明为IBOutlets。这意味着 Interface Builder 直接从 XIB 文件绑定这些变量。

    您定义的属性不是 IBOutlets。当您合成它们时,您会覆盖 getter/setter,并且 Interface Builder 无法再绑定到它们。

    要解决您的问题,请从您的成员变量中删除 IBOutlet 说明符并将您的属性声明更改为以下内容:

    @property (retain, nonatomic) IBOutlet UIView *view;
    @property (retain, nonatomic) IBOutlet UIButton *startButton;
    

    【讨论】:

    • 我同意,合成将为您的属性创建一个 getter 和 setter 方法,但没有 IBOutlet 它不会与 XIB 相关,并且因为您正在覆盖视图,所以您会得到一个空白。我认为即使您不触摸 UIViewController {UIViewController IBOutlet UIView *myView; 放置 IBOutlet 也会起作用。 IBOutlet UIButton *startButton; }
    【解决方案2】:

    基本问题是UIViewController 已经有一个view 属性。当您在 UIViewController 子类中重新定义它时,您会覆盖该视图属性。坦率地说,我很惊讶它甚至可以编译。

    修复:

    (1) 首先,问问自己,除了继承的视图属性之外,是否还需要另一个视图属性。如果您只需要控制器的一个视图,只需使用继承的属性。

    (2) 如果您确实需要第二个视图的参考,请将其命名为:

    #import <UIKit/UIKit.h>
    //@class View1Controller; <-- don't forward declare a class in its own header
    
    
    @interface View1Controller : UIViewController {
        // IBOutlet UIView *view; <-- this is inherited from UIViewController
        IBOutlet UIView *myView;
        IBOutlet UIButton *startButton;
    }
    //@property (retain, nonatomic) UIView *view; <-- this is inherited from UIViewController
    @property (retain, nonatomic) UIView *myView;
    @property (retain, nonatomic) UIButton *startButton;
    
    
    -(IBAction)startClock:(id)sender;
    
    @end
    

    然后在实现中:

    //@synthesize view; <-- this is inherited from UIViewController
    @synthesize myView, startButton;
    

    【讨论】:

    • +1,这件事发生在我身上……费了很多周折才找到,应该先咨询 Stack Overflow!
    猜你喜欢
    • 1970-01-01
    • 2013-10-26
    • 1970-01-01
    • 2014-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-12
    相关资源
    最近更新 更多