2016-08-10 3 views
-1

Я хотел бы добавить текстовое поле и кнопку отправки, которая придерживается нижней части uitableview, похожей на приложение чата. Я встретил комментарии о внедрении UITableView в виде контейнера в UIViewController.Внедрение UITableView в виде контейнера в UIViewController

Однако у них, похоже, нет примера о том, как этого достичь. Подробнее о деталях, в том числе о том, где добавить текстовое поле/кнопку и переместить текстовое поле вверх при появлении клавиатуры и т. Д. Спасибо!

+0

См этой недавней почта на [плавающую кнопке на 'UITableView'.] (Http://stackoverflow.com/questions/38887389/a-floating-button -fixed-at-the-bottom-of-uitableview-with-scrollviewdidscroll-no/38887755 # 38887755) Это может быть полезно. Его использование 'UITableViewController' вместо' UIViewController', хотя оно подходит по вашему требованию. –

ответ

0

код модели очень простой чат, вы можете взглянуть:

#import "ViewController.h" 

@interface ViewController() 

@property UIView* containerView; 

@end 

@implementation ViewController 

- (void)viewDidLoad { 
[super viewDidLoad]; 
// Do any additional setup after loading the view, typically from a nib. 

_containerView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds]; 

UITableView* tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-30)]; 
UITextField* tfInput = [[UITextField alloc] initWithFrame:CGRectMake(0, tableView.frame.size.height, [UIScreen mainScreen].bounds.size.width-50, 30)]; 
tfInput.backgroundColor = [UIColor grayColor]; 
UIButton* btnSend = [[UIButton alloc] initWithFrame:CGRectMake(tfInput.frame.size.width, tfInput.frame.origin.y, 50, 30)]; 
[btnSend setTitle:@"Send" forState:UIControlStateNormal]; 
[btnSend setTitleColor:[UIColor blueColor] forState:UIControlStateNormal]; 
[btnSend addTarget:self action:@selector(btnClicked) forControlEvents:UIControlEventTouchUpInside]; 

[_containerView addSubview:tableView]; 
[_containerView addSubview:tfInput]; 
[_containerView addSubview:btnSend]; 
[self.view addSubview:_containerView]; 

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; 
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil]; 
} 

- (void)keyboardWillShow:(NSNotification *)notification { 
NSDictionary *userInfo = [notification userInfo]; 
NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey]; 
float keyboardHeight = [aValue CGRectValue].size.height; 
//Resize the container 
_containerView.frame = CGRectMake(0, - keyboardHeight, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height); 
} 

-(void)btnClicked{ 
[self.view endEditing:YES]; 
} 

- (void)keyboardWillHide:(NSNotification *)notification { 
_containerView.frame = [UIScreen mainScreen].bounds; 
} 

- (void)didReceiveMemoryWarning { 
[super didReceiveMemoryWarning]; 
// Dispose of any resources that can be recreated. 
} 

@end 

Это скриншот для использования раскадровки:

enter image description here

+0

Спасибо! Есть ли способ заставить его работать с табличным представлением, встроенным в виде контейнера в viewcontroller через раскадровку (не созданный программно, как в приведенном выше примере)? – mir

+0

Это то же самое, что и программно, просто перетащите UIView в качестве контейнера, затем перетащите таблицу, текстовое поле, кнопку в контейнере один за другим, и, наконец, свяжите их с ViewContoller.h в качестве выхода (для кнопки вы можете просто использовать действие). Что касается события клавиатуры, вы должны использовать код для его завершения, как и выше. –

+0

Кстати, я предлагаю вам использовать код для создания вашего приложения, особенно для сложного пользовательского интерфейса, или у вас будет так много проблем, чтобы закончить его. –

3

выполните следующие действия с помощью раскадровки

1) drag a uiviewcontroller from the object library. 
2) drag and drop the textfield and button and place it at the position you want 
3) drag and drop a container view. 
4) delete the default uiviewcontroller comes with the container view 
5) drag a uitableviewcontroller and make a segue and the segue should be embedsegue. 

и для обработки клавиатуры вы можете пойти с IQKeyboardManager библиотеки https://github.com/hackiftekhar/IQKeyboardManager

Смежные вопросы