我有一个带有文本字段的表格 View ,当在文本字段中输入文本时,文本字段应该自动向上移动,就在键盘上方。
我在 stackoverflow 中看到很多解决方案都在文本字段委托(delegate)方法中编写逻辑。
我想分享将文本字段移动到键盘上方的解决方案没有任何逻辑。
此贴是为了把解决方法分享给大家。
此解决方案与此“How to make a UITextField move up when keyboard is present?”不同'
提前致谢。
最佳答案
我使用 LHSKeyboardAdjusting ,它不会占用您的 UITextField
委托(delegate)方法。许多库将接管您的委托(delegate),因此当 -[UITextFieldDelegate textFieldShouldReturn:]
被触发时,您无法执行诸如前进到下一个文本字段之类的操作。
LHSKeyboardAdjusting 监听键盘显示/隐藏事件并调整您传入的 View 的底部约束。很棒的是它适用于 UIView
和 UIScrollView
。
在您的 UIViewController
子类中,这是您设置它的方式(在这种情况下,我在 xib
中使用 UIScrollView
或 Storyboard
):
#import "UIViewControllerSubclass.h"
#import <LHSKeyboardAdjusting/UIViewController+LHSKeyboardAdjustment.h>
@interface UIViewControllerSubclass () <LHSKeyboardAdjusting>
@property (nonatomic, weak) IBOutlet UIScrollView *scrollView;
/** The constraint that anchors '_scrollView' bottom to '_view' bottom */
@property (nonatomic, weak) IBOutlet NSLayoutConstraint *scrollViewBottomConstraint;
@end
@implementation UIViewControllerSubclass
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self lhs_activateKeyboardAdjustment];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[self lhs_deactivateKeyboardAdjustment];
}
#pragma mark - LHSKeyboardAdjusting
- (NSLayoutConstraint *)keyboardAdjustingBottomConstraint {
return self.scrollViewBottomConstraint;
}
@end
关于ios - 在实现类中没有任何逻辑的情况下自动向上滚动文本字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26750058/