Clint
Clint

Reputation: 13

Add Button at the top of a view iOS programmatically

I am trying to program my app's view controller. It has buttons and textfields. I want to put my objects into another view (the one with color green background). The first Textfield should be at the very top of the green view.

I know how to make it center. But I need to put it starting at (0,0) of the green view.

Here's what I've done so far:

// add UI View For TextFields and Login Button
UIView *utc = [[UIView alloc] init];
utc.backgroundColor = [UIColor greenColor];
utc.frame = CGRectMake(0, 0, screenWidth * 0.95, 170);
utc.center = CGPointMake(screenWidth * 0.50, screenHeight * 0.68);
[self.view addSubview:utc];

// add textfield1
UITextField *emailTextField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, utc.frame.size.width, miniButtonWidth.height)];
emailTextField.center = CGPointMake(utc.frame.size.width * 0.5, utc.frame.size.height * 0.01);
emailTextField.borderStyle = UITextBorderStyleNone;
emailTextField.background = [UIImage imageNamed:@"textfieldLogIn.png"];
emailTextField.placeholder = @"Email Address";
emailTextField.backgroundColor = [UIColor clearColor];
[utc addSubview:emailTextField];

I'm using the same way (configuring the frame and center) of the views in my other Viewcontroller, and the design looks perfectly nice, just in this case, I can't put the textfield at the very top. I'm new in iOS.

enter image description here

Upvotes: 1

Views: 795

Answers (1)

keji
keji

Reputation: 5990

If you want emailTextField at the top left, but still centered, than just initialize it with those values and don't edit the center.

UITextField *emailTextField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, utc.frame.size.width, miniButtonWidth.height)];

emailTextField will be at the top left and you won't have to center it because it is already the width of the utc.

Upvotes: 1

Related Questions