2012-04-13 62 views
3

我有一個自定義單元,裏面有UITextView。我加載到此UITextView的文本的長度從很短變爲很長。所以請,不要說使用標籤,而不是」。我想保持單元格的高度相同,但如果文字太長,請使用UITextView的垂直滾動。如何垂直對齊UITextView中的文本?

我試過方法here但由於我在我的cellForRowAtIndexPath事件中使用自定義單元格初始化,所以觀察者不工作。我在initWithStyle函數下的單元格類中嘗試了同樣的方法,也沒有工作。

你還建議什麼?或者我應該以不同的方式使用這個功能?任何幫助表示讚賞。

在此先感謝。

+0

你可以參考下面的帖子,它爲我工作。 http://imagineric.ericd.net/2011/03/10/ios-vertical-aligning-text-in-a-uitextview/ – rishi 2012-04-13 10:28:50

+0

@RIP,請重新閱讀第二段,我已經在共享相同的鏈接我的問題,並宣佈爲什麼我不能讓它的工作... – kubilay 2012-04-13 10:32:33

回答

1

在你的TableView數據源 -

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    NSUInteger row = [indexPath row]; 

    static NSString *CellIdentifier = @"myCell"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; 
    } else { // if there is already a subview, remove it 
     while ([[cell.contentView subviews] count] > 0) { 
      UIView *labelToClear = [[cell.contentView subviews] objectAtIndex:0]; 
      [labelToClear removeFromSuperview]; 
     } 
    } 


    UITextView *myTextView = // initialise your textView here, including setting its contentOffset 

    [cell.contentView addSubview:myTextView]; 

    return cell; 

} 
+0

我一直在嘗試,但獲得空單元格。你如何看待這段代碼? http://pastebin.com/7yKZr2T9 – kubilay 2012-04-13 11:06:46

+0

你還沒有告訴它textView有多大 - 它的大小是0x0。你需要做UITextView * myTextView = [[[UITextView alloc] initWithFrame:whateverFrame] autorelease];另外,你的contentOffset工作方式是錯誤的 - 你可能希望x分量設置爲零,如果你將y設置爲textView的高度,它將向下偏移textView的高度,所以你無論如何都不會看到它!負值表示textView的頂部將位於原點之上。 – SomaMan 2012-04-13 11:20:05

+0

不完全如你所說,但主要是這樣,我做到了。非常感謝。 – kubilay 2012-04-13 11:42:07

2

使用此 -

CGSize textSize = [myText sizeWithFont:whateverFont constrainedToSize:myTextViewBox.frame.size lineBreakMode:UILineBreakModeWordWrap]; 

...然後找出contentOffset並將其設置爲你的UITextView添加到表。

+0

謝謝,但不知道如果我得到它。我應該動態添加textview嗎?你有這樣的代碼嗎? – kubilay 2012-04-13 10:29:22