在UIViewController中嵌入UITableView作为容器视图

时间:2016-08-10 16:05:16

标签: ios swift uitableview uiviewcontroller uicontainerview

我想添加一个文本字段和发送按钮,该按钮位于uitableview的底部,类似于聊天应用。我在UIViewController中嵌入了一个将UITableView作为容器视图嵌入的注释。

然而,他们似乎缺乏如何实现这一目标的例子。更具体地说,详细信息包括添加文本字段/按钮的位置以及键盘出现时向上移动文本字段等等。谢谢!

2 个答案:

答案 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

答案 1 :(得分: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