0

I'm trying to add my UITextField to a UIView that is placed in the centre of the table. The UIView works fine and is positioned correctly. however the UITextField is in the wrong position and at the bottom left of the screen. Code below:

    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];

When I am placing the UITextField in the centre of the UIView do the coordinates need to be inside the UIView's coordinates or the frames?

nburk
  • 22,409
  • 18
  • 87
  • 132
KexAri
  • 3,867
  • 6
  • 40
  • 80

2 Answers2

2

That's because addFriendView.center is it's center in it's superview coordinate which is {150, 25}. What you want is that put the center of nameField in the center of addFriendView in addFriendView's coordinate.

So, use this:

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

Updated to use CGRectGetMidX and CGRectGetMidY instead.

yusuke024
  • 2,189
  • 19
  • 12
  • More better is use CGRectGetMid* methods, them good for any rects: nameField.center = CGPointMake(CGRectGetMidX(addFriendView.bounds), CGRectGetMidY(addFriendView.bounds)); – Andrew Romanov Feb 11 '15 at 18:17
0

Because you have added nameField as a subview of self.addFriendView, its center will need to be relative to self.addFriendView.

nameField.center=self.view.center;

This line here is causing your issue. If fact, it's also an issue where you assign self.addFriendView's center, but by luck, self.view's bounds happen to be the same as its superview's.

Instead, you'll want to do this:

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

and also, just for robustness:

self.addFriendView.center=CGPointMake(CGRectGetMidX(self.view.bounds),
                                      CGRectGetMidY(self.view.bounds));
Ian MacDonald
  • 13,472
  • 2
  • 30
  • 51