我使用代码尝试设置标签文本,但它不起作用。我虽然可能忘记将插座与标签连接,或者我连接错误的插座但是一旦我检查它们就可以了。确保xib
已保存。
.m
@synthesize nameLabel;
@synthesize infoLabel;
-(void) updateUI
{
nameLabel.text = @"test1";
infoLabel.text = @"test2";
}
.h
UILabel * nameLabel;
UILabel * infoLabel;
@property(nonatomic, retain) IBOutlet UILabel *nameLabel;
@property(nonatomic, retain) IBOutlet UILabel *infoLabel;
几乎所有与这些标签相关的veiw控制器中使用的代码。有什么我想念的东西可以解释这种奇怪吗?
标签'name'中的默认文字& 'info'正在展示。
这是在调用updateUI之前调用的代码
browseDeckViewController.m
-(void) viewDidLoad
{
cardOnTopOfDeck = 0;
cardSecondFromTopOfDeck=1;
deck = [[Deck alloc] init];
[deck loadDeckData];
Card *mySecondCard = [[Card alloc] init];
mySecondCard = [deck.deckArray objectAtIndex:cardSecondFromTopOfDeck];
secondCard = [[CardViewController alloc] initWithNibName:@"CardViewController"
bundle:[NSBundle mainBundle] numberOfStats:kNumStats];
[secondCard setCard:mySecondCard];
CGRect frame = secondCard.view.frame;
frame.origin.x = (320-frame.size.width)/2;
frame.origin.y = 10;
secondCard.view.frame = frame;
[self.view addSubview:secondCard.view];
topCard = [[CardViewController alloc] initWithNibName:@"CardViewController"
bundle:[NSBundle mainBundle] numberOfStats:kNumStats];
Card *myTopCard = [[Card alloc] init];
myTopCard = [deck.deckArray objectAtIndex:cardOnTopOfDeck];
[topCard setCard:myTopCard];
frame = topCard.view.frame;
frame.origin.x = (320-frame.size.width)/2;
frame.origin.y = 10;
topCard.view.frame = frame;
[self.view addSubview:topCard.view];
}
CardViewController.m
-(void) setCard:(Card *)newCard
{
[card release];
card = [newCard retain];
[self updateUI];
}
-(void) updateUI
{
NSLog(@"updateUI");
nameLabel.text = @"test1";
infoLabel.text = @"test2";
}
答案 0 :(得分:2)
您的CardViewController
已创建,然后您立即尝试在该控制器的视图中设置UILabel
的文本。问题是,视图尚未加载。在调用updateUI
时,viewDidLoad:
尚未调用CardViewController
,这意味着nameLabel
和infoLabel
为nil
。< / p>
在尝试访问任何插座之前,必须强制CardViewController
的视图从NIB加载。一个简单的[self view];
就足够了。例如:
-(void) updateUI {
NSLog(@"nameLabel's value: %@",nameLabel); //nil here
[self view];
NSLog(@"nameLabel's value after loading view: %@",nameLabel); //Now it's loaded
nameLabel.text = @"test1";
infoLabel.text = @"test2";
}
修改强>
另一种解决方案是将updateUI
的呼叫转移到addSubview
之后:
myTopCard = [deck.deckArray objectAtIndex:cardOnTopOfDeck];
[self.view addSubview:topCard.view];
[topCard setCard:myTopCard];
frame = topCard.view.frame;
frame.origin.x = (320-frame.size.width)/2;
frame.origin.y = 10;
topCard.view.frame = frame;
答案 1 :(得分:1)
此代码不正确:
nameLabel.text = "test1";
infoLabel.text = "test2";
您正在为char*
变量分配NSString*
个指针;你需要在字符串前加上@
符号。
假设调用updateUI
方法,nameLabel
和infoLabel
在调用时都存在,这应该有效:
nameLabel.text = @"test1";
infoLabel.text = @"test2";