gpt4 book ai didi

objective-c - 设置UILABEL的初始值

转载 作者:行者123 更新时间:2023-12-01 17:35:00 24 4
gpt4 key购买 nike

我正在尝试创建一个简单的Quiz应用程序(我是初学者),当我启动该应用程序时,我希望UILabel显示(一系列问题中的)第一个问题。我在设置初始值时遇到了麻烦。

我已经做了几次尝试,成功实现了白色。我在我的QuizAppDelegate.h文件中声明了UILabel,如下所示:

 IBOutlet UILabel * questionField;

在我的主.m文件中,我尝试了以下操作:
- (id)init {

[super init];

questions = [[NSMutableArray alloc] init];

// Not working
questionField = [[UILabel alloc] init];
[questionField setText:@"Hello"];

// Working
NSLog(@"Hello");

[self defaultQuestions];
// [self showQuestion];

return self;
}

我尝试过的另一件事是QuizAppDelegate中的以下内容:
@property (nonatomic, retain) IBOutlet UILabel *questionField;

- (void)changeTitle:(NSString *)toName;

在.m文件中:
@synthesize questionField;

- (id)init {

[super init];

questions = [[NSMutableArray alloc] init];

// Not working
[self changeTitle:@"Hello"];

// Working
NSLog(@"Hello");

[self defaultQuestions];
// [self showQuestion];

return self;
}

-(void)changeTitle:(NSString *)toName {
[questionField setText:toName];
}

关于如何解决这个问题的任何技巧都将很棒!

//安德斯

最佳答案

希望您实际上没有将代码放入main.m中。在iOS上,您很少修改该文件。

由于您要在AppDelegate中完成所有操作,因此请保留其中(而不是创建新的UIViewController)。让我们从基础开始。

将Label添加为实例变量

您的操作正确无误-在.h文件的花括号内,将

IBOutlet UILabel * questionField;

然后,声明相应的属性,并确保在 .m文件中对其进行合成。
@property (nonatomic, retain) IBOutlet UILabel *questionField;
@synthesize questionField // in the .m file

在Interface Builder中添加UILabel

打开 MainWindow.xib。将UILabel从“库”拖到代表您的应用程序窗口的窗口中。然后从AppDelegate对象(在Xcode 4左侧的第三个图标;将在IB 3的Document窗口中将其标记)中进行Control-Drag。您会看到一个黑色的小窗口出现-选择名为 questionField的选项进行连接。

有关屏幕截图以及如何在IB中建立连接,请参见 this link。 Xcode 4中也是如此。

更改文本

您不需要更改文本的单独方法,只需修改标签的 text属性即可。

选择一种在应用程序启动时将被调用的方法( applicationDidFinishLaunching:WithOptions:是执行此操作的好地方),然后输入以下代码:
questionField.text = @"Hello";

就是这样!

代码

QuizAppDelegate.h
#import <UIKit/UIKit.h>

@interface QuizAppDelegate : NSObject <UIApplicationDelegate> {
IBOutlet UILabel *questionField;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UILabel *questionField;

@end

QuizAppDelegate.m
#import "QuizAppDelegate.h"

@implementation QuizAppDelegate

@synthesize window=_window;
@synthesize questionField;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
// Add the tab bar controller's current view as a subview of the window
[self.window addSubview:self.questionField];
[self.window makeKeyAndVisible];
self.questionField.text = @"Hello";
return YES;
}

- (void)dealloc
{
[_window release];
[questionField release];
[super dealloc];
}

@end

关于objective-c - 设置UILABEL的初始值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6311939/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com