ScrollView初步认识
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//一般通过代码设置
self.scrollView.contentSize = CGSizeMake(self.view.frame.size.width, 900);
self.textField.delegate = self;
}
- (void)viewDidAppear:(BOOL)animated{
[self.scrollView setContentOffset:CGPointMake(0, 110) animated:YES];
//注册键盘广播
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHide:) name:UIKeyboardDidHideNotification object:nil];
[super viewDidAppear:animated];
}
- (void)viewDidDisappear:(BOOL)animated{
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidHideNotification object:nil];
[super viewDidDisappear:animated];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark 放弃第一响应者
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return YES;
}
#pragma mark 键盘显示
- (void)keyboardDidShow:(NSNotification *)notif{
if (keyboardVisible) {
return;
}
//获得见键盘的尺寸
NSDictionary *info = [notif userInfo];
NSValue *aValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
CGSize keyboardSize = [aValue CGRectValue].size;
//重新定义ScorllView的尺寸
CGRect viewFrame = self.scrollView.frame;
viewFrame.size.height -= (keyboardSize.height);
self.scrollView.frame = viewFrame;
//滚动到当前文本框
CGRect textFieldRect = [self.textField frame];
[self.scrollView scrollRectToVisible:textFieldRect animated:YES];
keyboardVisible = YES;
}
#pragma mark 键盘隐藏
- (void)keyboardDidHide:(NSNotification *)notif{
NSDictionary *info = [notif userInfo];
NSValue *aValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
CGSize keyboardSize = [aValue CGRectValue].size;
CGRect viewFrame = self.scrollView.frame;
viewFrame.size.height += keyboardSize.height;
self.scrollView.frame = viewFrame;
if (!keyboardVisible) {
return;
}
keyboardVisible = NO;
}
//contentSize 内容的大小
//contentInset 给周围留的边框
//contentOffSet 偏移量
只要防止键盘覆盖TextField
本文介绍如何使用UIScrollView调整视图以适应键盘弹出的情况,并通过监听键盘通知实现TextField不会被键盘遮挡的效果。主要内容包括设置contentSize,监听键盘显示与隐藏的通知,以及调整scrollView的frame。
1793

被折叠的 条评论
为什么被折叠?



