【问题标题】:Can't centre UITextField in UIView无法在 UIView 中居中 UITextField
【发布时间】:2015-02-11 18:08:58
【问题描述】:

我正在尝试将我的UITextField 添加到位于表格中心的UIViewUIView 工作正常并且定位正确。但是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 的坐标或框架内?

【问题讨论】:

标签: ios xcode uiview uitextfield


【解决方案1】:

那是因为addFriendView.center 是它在其父视图坐标中的中心,即{150, 25}。你想要的是把nameField的中心放在addFriendView的中心addFriendView的坐标中。

所以,使用这个:

nameField.center = CGPointMake(CGRectGetMidX(addFriendView.bounds), 
                               CGRectGetMidY(addFriendView.bounds));

更新为使用CGRectGetMidXCGRectGetMidY

【讨论】:

  • 更好的是使用 CGRectGetMid* 方法,它们适用于任何矩形:nameField.center = CGPointMake(CGRectGetMidX(addFriendView.bounds), CGRectGetMidY(addFriendView.bounds));
【解决方案2】:

因为您已将nameField 添加为self.addFriendView 的子视图,所以它的中心需要相对于self.addFriendView

nameField.center=self.view.center;

这里的这一行导致了您的问题。事实上,分配self.addFriendViewcenter 也是一个问题,但幸运的是,self.view 的边界恰好与其父视图的边界相同。

相反,您需要这样做:

nameField.center=CGPointMake(CGRectGetMidX(self.addFriendView.bounds),
                             CGRectGetMidY(self.addFriendView.bounds));

而且,只是为了稳健:

self.addFriendView.center=CGPointMake(CGRectGetMidX(self.view.bounds),
                                      CGRectGetMidY(self.view.bounds));

【讨论】:

    猜你喜欢
    • 2021-03-27
    • 2013-04-11
    • 1970-01-01
    • 2011-07-04
    • 2013-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多