2014-03-06 38 views
0

我有一個包含聊天室的應用程序。每次有人輸入內容時,我都希望它向下滾動到輸入的最後一行。基本上,我希望鍵入的最後一個東西是屏幕上最低的東西。當我像十行聊天文本一樣打字時,它就會直接在我的視線下面。這裏是我的代碼:iPhone - 在聊天室向下滾動線條

- (void)scrollToBottom 
{ 
    CGRect lastLine; 
    lastLine.origin.x = 0; 
    lastLine.origin.y = self.contentSize.height-1; 
    lastLine.size.height = 1; 
    lastLine.size.width = 1; 

    [self scrollRectToVisible:lastLine animated:NO]; 
} 

我把這個使用此代碼發佈的內容後:

- (void)displayChatMessage:(NSString*)message fromUser:(NSString*)userName { 
     [chat appendTextAfterLinebreak:[NSString stringWithFormat:@"%@: %@", userName, message]]; 
     [chat scrollToBottom]; 
} 

當我打電話appendTextAfterLinebreak以和爲代碼是:

- (void)appendTextAfterLinebreak:(NSString *)text 
{ 
    self.text = [[self.text stringByAppendingString:@"\n"] stringByAppendingString:text]; 
} 
+0

您使用的是UITextView嗎? –

+0

@LyndseyScott我編輯的帖子,包括進一步的代碼,如果這有幫助 – user2779450

+0

更有幫助,但仍然不夠好......什麼樣的結構是「聊天」?你必須使用scrollview或textview,如果你能夠滾動和追加文本... –

回答

0

假設您正在使用UITextView,您可以使用scrollRangeToVisible:來輕鬆地滾動到最後一行。例如:

- (void)scrollToBottom { 

    NSRange bottom = NSMakeRange(chat.text.length - 1, 1); 
    [chat scrollRangeToVisible:bottom]; 

} 
+0

我身份證,但它很奇妙地滾動到頂部,每次我輸入的東西,然後在第二個或第二個滾動回滾到底部 – user2779450

+0

在scrollToVisible被調用之前還是之後向上滾動? –

+0

它滾動後 – user2779450

0

假設您使用的是UIScrollView,您可以使用下面的代碼。

- (void)scrollToBottomAnimated:(BOOL)animated { 
    CGFloat y = myScrollView.contentSize.height - myScrollView.frame.size.height; 
    [myScrollView setContentOffset:CGPointMake(0, y) animated:animated]; 
} 
+0

我更新了我的帖子。看看我上傳的新代碼。我不認爲我正在使用UIScrollView – user2779450