Ответ 1
Проверьте эти ответы:
Как создать многострочное поле UIText?
Как создать многострочное поле UIText?
http://brettschumann.com/blog/2010/01/15/iphone-multiline-textbox-for-sms-style-chat
И определенно попробуйте Three20, который является большой библиотекой, используемой во многих приложениях, таких как Facebook.
Изменить: добавлен отрывок из блога BrettSchumann
#import <uikit uikit.h="">
@interface MultilineTextboxViewController : UIViewController {
IBOutlet UIView *viewTable;
IBOutlet UIView *viewForm;
IBOutlet UITextView *chatBox;
IBOutlet UIButton *chatButton;
}
@property (nonatomic, retain) UIView *viewTable;
@property (nonatomic, retain) UIView *viewForm;
@property (nonatomic, retain) UITextView *chatBox;
@property (nonatomic, retain) UIButton *chatButton;
- (IBAction)chatButtonClick:(id)sender;
@end
</uikit>
С этим и пока мы все настраиваем, давайте переходим и добавляем наши элементы в наш основной (.m) файл одновременно, не забывая также их деблокировать.
@synthesize viewTable;
@synthesize viewForm;
@synthesize chatBox;
@synthesize chatButton;
- (void)dealloc{
[viewTable release];
[viewForm release];
[chatBox release];
[chatButton release];
[super dealloc];
}
В методе (void) viewDidLoad нам нужно добавить некоторых наблюдателей уведомлений, чтобы мы могли видеть, когда клавиатура отображается или скрыта, и когда пользователь нажимает клавишу на клавиатуре.
- (void)viewDidLoad {
//set notification for when keyboard shows/hides
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
//set notification for when a key is pressed.
[[NSNotificationCenter defaultCenter] addObserver:self
selector: @selector(keyPressed:)
name: UITextViewTextDidChangeNotification
object: nil];
//turn off scrolling and set the font details.
chatBox.scrollEnabled = NO;
chatBox.font = [UIFont fontWithName:@"Helvetica" size:14];
[super viewDidLoad];
}
Когда фокус установлен в текстовом режиме, клавиатура будет отображаться. Поскольку текстовое изображение и кнопки находятся в нижнем представлении на экране, клавиатура будет двигаться вверх и перебирать их. Поэтому мы хотим настроить высоту viewTable и позицию viewForm. Мы делаем это следующим образом.
-(void) keyboardWillShow:(NSNotification *)note{
// get keyboard size and loction
CGRect keyboardBounds;
[[note.userInfo valueForKey:UIKeyboardBoundsUserInfoKey] getValue: &keyboardBounds];
// get the height since this is the main value that we need.
NSInteger kbSizeH = keyboardBounds.size.height;
// get a rect for the table/main frame
CGRect tableFrame = viewTable.frame;
tableFrame.size.height -= kbSizeH;
// get a rect for the form frame
CGRect formFrame = viewForm.frame;
formFrame.origin.y -= kbSizeH;
// animations settings
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:0.3f];
// set views with new info
viewTable.frame = tableFrame;
viewForm.frame = formFrame;
// commit animations
[UIView commitAnimations];
}
Теперь, когда клавиатура отображается и наши представления были скорректированы, мы хотим захватить текст, который вводим пользователь, и посмотреть, нужно ли нам вносить какие-либо корректировки в chatBox. К счастью для нас, мы можем использовать объект CGSize, передать ему некоторый текст и сообщить объекту, какой размер мы хотели бы ограничить текстом, и из которого мы можем вычислить, получить высоту. Теперь это где небольшая пробная версия и ошибка. Строка варьируется в зависимости от размера шрифта, и ваша ширина объекта CGSize будет меняться в зависимости от ширины вашего UITextview, поэтому вам придется немного поэкспериментировать. Значение 12, используемое в приведенном ниже коде, - это разница в высоте между начальной высотой моего chatBox и высотой строки на основе шрифта, который я установил.
-(void) keyPressed: (NSNotification*) notification{
// get the size of the text block so we can work our magic
CGSize newSize = [chatBox.text
sizeWithFont:[UIFont fontWithName:@"Helvetica" size:14]
constrainedToSize:CGSizeMake(222,9999)
lineBreakMode:UILineBreakModeWordWrap];
NSInteger newSizeH = newSize.height;
NSInteger newSizeW = newSize.width;
// I output the new dimensions to the console
// so we can see what is happening
NSLog(@"NEW SIZE : %d X %d", newSizeW, newSizeH);
if (chatBox.hasText)
{
// if the height of our new chatbox is
// below 90 we can set the height
if (newSizeH <= 90)
{
[chatBox scrollRectToVisible:CGRectMake(0,0,1,1) animated:NO];
// chatbox
CGRect chatBoxFrame = chatBox.frame;
NSInteger chatBoxH = chatBoxFrame.size.height;
NSInteger chatBoxW = chatBoxFrame.size.width;
NSLog(@"CHAT BOX SIZE : %d X %d", chatBoxW, chatBoxH);
chatBoxFrame.size.height = newSizeH + 12;
chatBox.frame = chatBoxFrame;
// form view
CGRect formFrame = viewForm.frame;
NSInteger viewFormH = formFrame.size.height;
NSLog(@"FORM VIEW HEIGHT : %d", viewFormH);
formFrame.size.height = 30 + newSizeH;
formFrame.origin.y = 199 - (newSizeH - 18);
viewForm.frame = formFrame;
// table view
CGRect tableFrame = viewTable.frame;
NSInteger viewTableH = tableFrame.size.height;
NSLog(@"TABLE VIEW HEIGHT : %d", viewTableH);
tableFrame.size.height = 199 - (newSizeH - 18);
viewTable.frame = tableFrame;
}
// if our new height is greater than 90
// sets not set the height or move things
// around and enable scrolling
if (newSizeH > 90)
{
chatBox.scrollEnabled = YES;
}
}
}
После того, как мы и пользователь нажмем кнопку отправки, мы хотим что-то сделать с нашим текстом, ключевое слово исчезнет, и мы хотим, чтобы reset наш взгляд вернулся, как они были. Итак, как мы это делаем?
- (IBAction)chatButtonClick:(id)sender{
// hide the keyboard, we are done with it.
[chatBox resignFirstResponder];
chatBox.text = nil;
// chatbox
CGRect chatBoxFrame = chatBox.frame;
chatBoxFrame.size.height = 30;
chatBox.frame = chatBoxFrame;
// form view
CGRect formFrame = viewForm.frame;
formFrame.size.height = 45;
formFrame.origin.y = 415;
viewForm.frame = formFrame;
// table view
CGRect tableFrame = viewTable.frame;
tableFrame.size.height = 415;
viewTable.frame = tableFrame;
}
ResignFirstResponder собирается скрыть клавиатуру, а затем все, что нам нужно сделать, - установить представления и chatBox обратно в их исходные состояния.
-(void) keyboardWillHide:(NSNotification *)note{
// get keyboard size and loction
CGRect keyboardBounds;
[[note.userInfo valueForKey:UIKeyboardBoundsUserInfoKey] getValue: &keyboardBounds];
// get the height since this is the main value that we need.
NSInteger kbSizeH = keyboardBounds.size.height;
// get a rect for the table/main frame
CGRect tableFrame = viewTable.frame;
tableFrame.size.height += kbSizeH;
// get a rect for the form frame
CGRect formFrame = viewForm.frame;
formFrame.origin.y += kbSizeH;
// animations settings
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:0.3f];
// set views with new info
viewTable.frame = tableFrame;
viewForm.frame = formFrame;
// commit animations
[UIView commitAnimations];
}
И вот вы, текстовое представление, которое начинается как одна строка и растет в размере, когда пользователь вводит текст до максимального размера, прежде чем перейти в прокручиваемое текстовое представление.