UILabel nameLabel.text =“test1”;不工作,插座连接

时间:2010-09-11 23:45:53

标签: iphone objective-c xcode

我使用代码尝试设置标签文本,但它不起作用。我虽然可能忘记将插座与标签连接,或者我连接错误的插座但是一旦我检查它们就可以了。确保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";
   }

2 个答案:

答案 0 :(得分:2)

您的CardViewController已创建,然后您立即尝试在该控制器的视图中设置UILabel的文本。问题是,视图尚未加载。在调用updateUI时,viewDidLoad:尚未调用CardViewController,这意味着nameLabelinfoLabelnil。< / 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方法,nameLabelinfoLabel在调用时都存在,这应该有效:

nameLabel.text = @"test1";
infoLabel.text = @"test2";