看!经过2天的搜索,我相信我可能会有答案。诚然,没有代码就无法完成。
首先创建从 contentView 到 Scroll 视图的常用顶部、底部、前导和尾随约束。
但是,使用前导和尾随,勾选“占位符 - 构建时删除”选项。
然后在您的 viewDidLoad 方法中添加以下内容:
NSLayoutConstraint *leftConstraint =[NSLayoutConstraint
constraintWithItem:self.contentView
attribute:NSLayoutAttributeLeading
relatedBy:0
toItem:self.view
attribute:NSLayoutAttributeLeft
multiplier:1.0
constant:0];
[self.view addConstraint:leftConstraint];
NSLayoutConstraint *rightConstraint =[NSLayoutConstraint
constraintWithItem:self.contentView
attribute:NSLayoutAttributeTrailing
relatedBy:0
toItem:self.view
attribute:NSLayoutAttributeRight
multiplier:1.0
constant:0];
[self.view addConstraint:rightConstraint];
这会将 contentView 中的前导和尾随约束动态添加到控制器的主视图(即在滚动视图之外)。
然后,当您旋转设备时,输入字段会被适当地拉伸。
这解决了您的旋转问题,关于出现在 SO 上的其他答案的键盘,但基本上在 viewDidLoad 内部:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardDidHideNotification object:nil];
然后添加这2个方法:
- (void) keyboardWasShown:(NSNotification *)notification
{
NSDictionary *info = [notification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0);
self.scrollView.contentInset = contentInsets;
self.scrollView.scrollIndicatorInsets = contentInsets;
}
- (void) keyboardWillBeHidden:(NSNotification *)notification
{
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
self.scrollView.contentInset = contentInsets;
self.scrollView.scrollIndicatorInsets = contentInsets;
}