ios - 无法在 UIView 中将 UITextField 居中

标签 ios xcode uiview uitextfield

我正在尝试将我的 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));

已更新为使用 CGRectGetMidXCGRectGetMidY

关于ios - 无法在 UIView 中将 UITextField 居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28461333/

相关文章:

xcode - xcrun clang --sysroot 找不到 stdio.h

iPhone - viewDidLoad/viewDidAppear 中的 UIView 动画问题

ios - 如何使用 UIAlertController

objective-c - 我可以在旧版本的 iOS 上使用 ARC 吗?

ios - 如何推送不在导航 Controller 中的 View Controller ? swift

xcode - 如何在 Xcode Debugger 中调用嵌套的 Swift 函数?

ios - SpriteKit : Could not find an overload for 'runAction' that accepts the supplied arguments

ios - 如何从 UITableView 应用程序的详细 View 中删除当前行?

ios - 如何在 Swift 中以编程方式更改自定义 UITableViewCell 中按钮的背景颜色?

iOS:下拉看logo