2011-08-01 64 views
0

我在UIButton中使用插入標籤addSubViewiphone:標籤值超過寫。

這裏標籤的值每次都會改變。

UILabel *backTopLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 30, 448, 66)]; 
    backTopLabel.backgroundColor = [UIColor clearColor]; 
    backTopLabel.textColor = [UIColor whiteColor]; 
    backTopLabel.font = [UIFont fontWithName:@"Georgia" size:56]; 
    backTopLabel.textAlignment = UITextAlignmentCenter; 

    backTopLabel.text = [[selectedUsers objectAtIndex:userIndex] valueForKey:@"FirstName"]; // UserIndex will be change and new data will be load in the label 


    [btnBackLeftCard addSubview:backTopLabel]; // btnBackLeftCard is the UIButton 
    [backTopLabel release]; 

問題是:它成功地更改了標籤值,但它已經寫完了。

我正在通過舊標籤值獲取新標籤值。

我該如何解決這個問題?

+0

你要更改標籤,每次運行的代碼塊? – JonB

+0

是的,我每次運行此代碼。 – Devang

+0

在添加新文本之前添加以下行: ** backTopLabel.text = @「」; ** backTopLabel.text = [[selectedUsers objectAtIndex:userIndex] valueForKey:@「FirstName」]; // UserIndex將被更改並且新數據將被加載到標籤中並且請不要分配它再次只是做它一次或更好地使它的屬性 – rptwsthi

回答

4

每次通話時間[[UILabel alloc] initWithFrame:CGRectMake(0, 30, 448, 66)]要創建新的記憶,不訪問現有的內存。

所以,你需要有像

if(!backTopLabel) 
    backTopLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 30, 448, 66)]; 

,所以你只當它不存在創建的內存。

但是,由於您的標籤不是屬性,因此無論如何您基本上都無法訪問它。 因此,您需要將標籤添加爲您所在課程的屬性或標記視圖,以便您可以再次找到它&將其刪除。

標籤它&再次找到這樣的:

for(UIView* labelView in btnBackLeftCard.subviews) 
{ 
    if(labelView.tag = 100) 
     [labelView removeFromSuperView]; 
} 

UILabel *backTopLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 30, 448, 66)]; 
backTopLabel.backgroundColor = [UIColor clearColor]; 
backTopLabel.textColor = [UIColor whiteColor]; 
backTopLabel.font = [UIFont fontWithName:@"Georgia" size:56]; 
backTopLabel.textAlignment = UITextAlignmentCenter; 

//here is where you tag the view, so you can find it again 
backTopLabel.view.tag = 100; 

backTopLabel.text = [[selectedUsers objectAtIndex:userIndex] valueForKey:@"FirstName"]; 

[btnBackLeftCard addSubview:backTopLabel]; // btnBackLeftCard is the UIButton 
[backTopLabel release]; 
+0

很棒的回答。謝謝 – Devang

+0

謝謝。我建議自己製作該標籤屬性,但這取決於您。要麼會工作。 –

1

假設你只有一個子視圖中的UIButton插入您可以使用

for(UILabel *lblViews in [btn subviews]) //Remove all subviews which are labels under button first if any 
{ 
     if(lblViews.tag == sometagno) //Compare tag number and remove only if that label found. 
       [lblViews removeFromSuperview]; 
} 

backTopLabel.tag = sometagno; //Assign some tag number while adding. 
[btnBackLeftCard addSubview:backTopLabel]; //Than Add your subview 
+0

這也是刪除按鈕圖像!任何其他的想法? – Devang

+0

如下所示,您可以使用相同的標籤。如果你還沒有找到任何解決方案,你可以參考我的更新的想法。 –

+0

感謝它的工作 – Devang

0

這基本上發生在一個視圖被添加作爲另一種觀點子視圖。在你的情況下,它被添加多次。

創建一個UILabel,然後簡單地更改它的文本屬性。

在你的情況下,你多次創建它,並在前一個上面添加。

或者,如果你不能重複使用以前創建的一個,嘗試從上海華盈刪除它,然後添加最新的..

0

我覺得你再次添加子視圖(的UILabel)。 YOu應該只改變UILabel的文本

0

我在COCOS2D工作。如果您已聲明標籤全球然後用

[labelName removeFromParentAndCleanup:YES]