2013-03-13 25 views
2

我有一個UIPickerView,它將顯示用戶的項目列表。我希望每個項目都以多行文本形式顯示,每行使用不同的字體大小。一個粗糙的模型如下所示。這將允許呈現更多的文本,而不是默認UIPickerView的單行內容。UIPickerView - 使用多線行的自定義視圖 - 需要佈局建議

mockup

bdesham指着我對使用pickerView:viewForRow:forComponent:reusingView在委託的UIPickerView。這似乎是要走的路,因爲它可以讓我爲各行提供自己的自定義視圖。

我的想法是創建一個UIView,其中有2個UILabel子視圖,每行一個文本。這樣我可以對每一行應用不同的字體。我嘗試了下面,但佈局似乎沒有工作。我需要線條成爲另一條線。下面是我試圖通過面具將第二行浮動到底部。

#define VIEWTAG_LINE1 1 
#define VIEWTAG_LINE2 2 

- (UIView*)pickerView:(UIPickerView *)thePickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view 
{ 
    UIView* v; 
    if (view) 
     v = view; 
    else 
    { 
     v = [[[UIView alloc] init] autorelease]; 

     UILabel* l1 = [[[UILabel alloc] init] autorelease]; 
     l1.tag = VIEWTAG_LINE1; 
     [v addSubview: l1]; 

     UILabel* l2 = [[[UILabel alloc] init] autorelease]; 
     l2.tag = VIEWTAG_LINE2; 
     l2.autoresizingMask = UIViewAutoresizingFlexibleTopMargin; 
     [v addSubview: l2]; 
    } 

    UILabel* l1 = (UILabel*)[v viewWithTag: VIEWTAG_LINE1]; 
    l1.text = [NSString stringWithFormat: @"row %d line 1", row]; 
    [l1 sizeToFit]; 

    UILabel* l2 = (UILabel*)[v viewWithTag: VIEWTAG_LINE2]; 
    l2.text = [NSString stringWithFormat: @"row %d line 2", row]; 
    [l2 sizeToFit]; 

    [v sizeToFit]; 

    return v; 
} 

這產生了下面的內容。有關獲取兩個UILabel視圖的任何建議,以便它們堆疊在一起形成所需的多行結果?

multi-line attempt

+1

它可能無法正常工作,但你有沒有試過在UITableViewCell而不是簡單的UIView?因爲它確實正是你想要做風格明智的。 – HermioneGreen 2013-03-13 20:38:50

回答

3

您需要設置兩個標籤的框架和字體。

v = [[[UIView alloc] init] autorelease]; 

    UILabel* l1 = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 24)] autorelease]; 
    li.font = [UIFont sytemFontOfSize:22]; // choose desired size 
    l1.tag = VIEWTAG_LINE1; 
    [v addSubview: l1]; 

    UILabel* l2 = [[[UILabel alloc] initWithFrame:CGRectMake(0, 24, 320, 16)] autorelease]; 
    l2.font = [UIFont sytemFontOfSize:14]; // choose desired size 
    l2.tag = VIEWTAG_LINE2; 
    [v addSubview: l2]; 

根據需要調整標籤的高度。根據需要調整y來源l2

+0

請注意,我必須刪除autoresizingMask行才能使用。使用它仍然給出了奇怪的結果。第一行的第二行顯示在第二行,第二行的第二行顯示在第三行,等等。第二行被推下太多。刪除autoresizingMask使其工作並按預期顯示。 – Nerdtron 2013-03-14 17:15:41

+0

我應該使用320以外的硬編碼值嗎?此外,在x位置使用0仍然會導致標籤與控制圖形的左邊緣重疊。我將其更改爲4並且可行,但我想知道是否有某個地方需要查詢,而不是對其進行硬編碼。任何想法? – Nerdtron 2013-03-14 17:16:45

+1

奇怪的是,我甚至沒有注意到'autoresizingMask'的調用。可悲的是,沒有一種方法可以爲幀獲得更多動態值。有一件事會幫助的是將標籤的背景色設置爲「clearColor」。 – rmaddy 2013-03-14 17:19:44

1

如果有人遇到了自動佈局的問題,請將translatesAutoresizingMaskIntoConstraints設置爲YES(這是默認值)。我將它設置爲NO,這導致了所有問題。