KexAri
KexAri

Reputation: 3977

Can't centre UITextField in UIView

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?

Upvotes: 0

Views: 135

Answers (2)

yusuke024
yusuke024

Reputation: 2219

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.

Upvotes: 2

Ian MacDonald
Ian MacDonald

Reputation: 14010

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

Upvotes: 0

Related Questions