2011-05-23 47 views
0

對不起,初學者的問題:如何將相同的子視圖添加到不同的視圖?

我已經創建了一個UILabel的實例,並且想將這個UILabel的副本添加到4個不同的視圖。我嘗試了下面的代碼,但它不起作用,因爲我將UILabel分配給一個視圖,然後將其分配給下一個 - 這會導致UILabel從第一個視圖中刪除。此進行,所以我結束與的UILabel被分配只有到最後的觀點:

UILabel *titleTitle = [[[UILabel alloc] initWithFrame:CGRectMake(120, -48, 100, 28)] autorelease]; 
titleTitle.text = @"Index"; 
titleTitle.textColor = [UIColor blackColor]; 
titleTitle.backgroundColor = [UIColor clearColor]; 
titleTitle.font = [UIFont fontWithName:@"Ballpark" size:25.0f]; 
[indexView addSubview:titleTitle]; 
[indexView2 addSubview:titleTitle]; 
[indexView3 addSubview:titleTitle]; 
[indexView4 addSubview:titleTitle]; 

如何管理到的UILabel的拷貝分配給我的意見?

回答

3

這可能是爲您的需要矯枉過正,但如果你必須複製一個複雜的對象,然後封存和解除封存它應該工作:

NSMutableData *myData = [NSMutableData data]; 
NSKeyedArchiver *archiver = [[[NSKeyedArchiver alloc] initForWritingWithMutableData:myData] autorelease]; 

[archiver encodeObject:titleTitle forKey:@"myTitle"]; 
[archiver finishEncoding]; 
NSKeyedUnarchiver *unarchiver = [[[NSKeyedUnarchiver alloc] initForReadingWithData:myData] autorelease]; 


UILabel *t2 = [unarchiver decodeObjectForLey:@"myTitle"]; 
// set location attributes 
[view addSubView:t2]; 
[t2 release]; 

UILabel *t3 = [unarchiver decodeObjectForLey:@"myTitle"]; 
// set location attributes 
[view addSubView:t3]; 
[t3 release]; 

[unarchiver finishDecoding]; // Should be called once you will not decode any other objects 
1

這是不可能的,一個視圖只能有一個父母。

您需要將其從當前父項中移除以將其添加到別處。

5

你不能這樣做。一個視圖只能有一個父項。如果您想定義一次標籤並在多個地方使用類似定義的標籤,則應複製它。

編輯:@Michael Petrov指出UIView及其子類不符合NSCopying協議。我忽視了這一點。

如果他提供的答案對您來說太複雜了,您可以創建一個幫助函數,爲您生成一個新的UILabel實例。

-(UILabel *) generateLabel:(CGRect) location { 
    UILabel *label= [[[UILabel alloc] initWithFrame:location] autorelease]; 
    label.text = @"Index"; 
    label.textColor = [UIColor blackColor]; 
    label.backgroundColor = [UIColor clearColor]; 
    label.font = [UIFont fontWithName:@"Ballpark" size:25.0f]; 

    return label; 
} 

從你的代碼:

UILabel *l1 = [self generateLabel:CGRectMake(...)]; 
[self addToSubView:l1]; 
[l1 release]; 

UILabel *l2 = [self generateLabel:CGRectMake(...)]; 
[self addToSubView:l2]; 
[l2 release]; 

..等等。

+3

的UIView及其後代通常不支持NSCopying協議。 NSCoding是正確的方式)。 – 2011-05-23 19:45:01

+0

@Michael Petrov:那麼我如何在這種情況下使用NSCoding? [titleTitle副本]不起作用,對吧? – 2011-05-23 19:49:57

+2

我喜歡你的答案,因爲它是更正確和有效的方式來做事情,特別是作爲標籤的簡單事情。歸檔和非歸檔是一種非常繁瑣的策略,應該只用於複製大型嵌套UIViews樹(然後才能仔細考慮)。 – 2011-05-23 20:16:30

1

視圖只能在一個父視圖中顯示。所以你需要爲每個父視圖創建不同的標籤。您可以通過編寫幫助功能來減少打字量。

相關問題