gpt4 book ai didi

ios - 在中心使用键盘和自动布局管理 View

转载 作者:塔克拉玛干 更新时间:2023-11-02 10:32:21 28 4
gpt4 key购买 nike

我有以下 View 层次结构。 View->container->2 个 UITextfieldscontainerView 中的 1 个 button。容器位于屏幕中央。我想要做的是在键盘出现并且 UITextfield 位于键盘后面时向上移动容器,并在键盘消失时移回中心。这是相同的屏幕截图。

enter image description here

我需要更改哪些约束或需要在代码中添加约束?

最佳答案

在键盘显示时获取容器的框架并更新新的框架大小。 “setTranslatesAutoresizingMaskIntoConstraints”是更新 View 框架时的正确解决方案。它对我有用

enter image description here

 @implementation ViewController
{
CGRect defaultFrame;
}

- (void)viewDidLoad {
[super viewDidLoad];

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

- (void)keyboardWillShow:(NSNotification *)notification {
CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
defaultFrame = self.ContentView.frame;

[self.ContentView setTranslatesAutoresizingMaskIntoConstraints:YES];
[self.ContentView layoutIfNeeded];

CGRect contentInsets = CGRectMake(defaultFrame.origin.x, (keyboardSize.height), defaultFrame.size.width, defaultFrame.size.height);
[UIView animateWithDuration:0.5f
animations:^{
self.ContentView.frame = contentInsets;

}
completion:^(BOOL finished){

}
];

self.ContentView.frame = contentInsets;

}

- (void)keyboardWillHide:(NSNotification *)notification {
[self.ContentView setTranslatesAutoresizingMaskIntoConstraints:NO];
[UIView animateWithDuration:0.5f
animations:^{
self.ContentView.frame = defaultFrame;
}
completion:^(BOOL finished){

}
];

}

关于ios - 在中心使用键盘和自动布局管理 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36740564/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com