0

我试图以编程方式添加一个 UILabel (我用 IB 完成了它并且它有效)。但我不知道为什么它不显示。我以编程方式添加了一个按钮,效果很好。我希望按钮用随机报价更新标签。怎么了?

.h 文件:

@interface SecondViewController : UIViewController
{
    NSArray *citatDatabas;

}

@property (weak, nonatomic) IBOutlet UIButton *helloButton;
@property (weak, nonatomic) IBOutlet UIButton *citatKnapp;
@property (weak, nonatomic) IBOutlet UILabel *label1;

- (void)helloButtonPressed;
- (IBAction)citatKnappPressed:(id)sender;

@end

执行:

@implementation SecondViewController
@synthesize helloButton, citatKnapp, label1;

- (void)loadView {
    [super loadView]; 
citatDatabas = [NSArray arrayWithObjects:
                    [NSString stringWithFormat:@"%@", @"People ask me, would you rather be feared or loved, um easy, I want people to be afriad of how much they love me - Michael Scott" ],
                    [NSString stringWithFormat:@"%@", @"You miss 100% of all the shoots you dont take - Wayne Greatsky - Michael Scott" ],
                    [NSString stringWithFormat:@"%@", @"DONT PANIC - hitchhiker's guide to the galaxy" ],
                    [NSString stringWithFormat:@"%@", @"Give someone a mask and they'll show their true face - Oscar Wilde" ],
                    [NSString stringWithFormat:@"%@", @"Given enough time, hydrogen starts to wonder where it came from, and where it is going" ],
                    [NSString stringWithFormat:@"%@", @"You have just begun reading the sentence you just finished reading" ],
                    nil];



    self.citatKnapp = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    self.citatKnapp.frame = CGRectMake(98, 162, 124, 37);
    [self.citatKnapp setTitle:@"Tryck för citat" forState:UIControlStateNormal];
    [self.citatKnapp addTarget:self action:@selector(citatKnappPressed:)     forControlEvents:UIControlEventTouchUpInside];

    self.citatKnapp.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;

    [self.view addSubview:self.citatKnapp];

    self.label1 = [[UILabel alloc]initWithFrame:CGRectMake(20, 71, 200, 83)];

    self.label1.frame = CGRectMake(20, 71, 200, 83);
    self.label1.text = @"hej";
    self.label1.backgroundColor = [UIColor greenColor];
    [self.view addSubview:self.label1];


}

- (IBAction)citatKnappPressed:(id)sender{

    self.label1.text = [citatDatabas objectAtIndex:
                  (random() % [citatDatabas count])];
}

@end
4

2 回答 2

2

您的标签即将发布,请使用@property (strong, nonatomic) IBOutlet UILabel *label1;

如果您在分配 label1 后的任何行上放置一个断点,您将看到 label1 为 nil

于 2012-09-13T18:09:11.440 回答
0

loadView 中的原因,你的视图没有初始化。它是通过 XIB/StoryBoard 连接的吗?

如果不,

只需将您的视图初始化为方法中的第一行,为其添加标签

self.view = [[UIView alloc]initWithFrame:CGRectMake(0,0,320,480)];

然后写下你剩下的代码

于 2012-09-13T18:04:28.427 回答