我正在尝试将我的 UITextField
添加到放置在表格中央的 UIView
中。 UIView
工作正常并且位置正确。但是 UITextField
的位置错误,位于屏幕的左下角。代码如下:
self.addFriendView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 50)];
self.addFriendView.center=self.view.center;
[self.addFriendView setBackgroundColor:[UIColor whiteColor]];
UITextField *nameField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 280, 40)];
nameField.delegate=self;
nameField.center=self.view.center;
nameField.placeholder=@"enter username";
[self.addFriendView addSubview:nameField];
[self.tableView.superview addSubview:self.addFriendView];
当我将 UITextField
放在 UIView
的中心时,坐标是否需要在 UIView
的坐标或框架?
最佳答案
那是因为 addFriendView.center
是它的 super View 坐标的中心,它是 {150, 25}
。你想要的是将 nameField
的中心放在 addFriendView
的中心在 addFriendView
的坐标中。
所以,使用这个:
nameField.center = CGPointMake(CGRectGetMidX(addFriendView.bounds),
CGRectGetMidY(addFriendView.bounds));
已更新为使用 CGRectGetMidX
和 CGRectGetMidY
。
关于ios - 无法在 UIView 中将 UITextField 居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28461333/