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)];

次に、残りのurコードを記述します

于 2012-09-13T18:04:28.427 に答える