Nosrettap
Nosrettap

Reputation: 11340

Autoresizing UIViews inside UITableViewCell

I have subclassed a UITableView Cell and I want to programmatically add a UITextField to it. I have figured out how to create the text field; however, I'm having difficulty resizing it when the device gets rotated. Here is my code (keep in mind that self is a UITableViewCell subclass)

self.myTextField = [[UITextField alloc] init];
self.myTextField.frame = CGRectMake(400, 6,TEXT_FIELD_WIDTH ,TEXT_FIELD_HEIGHT);
[self addSubview:self.myTextField];
self.myTextField.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin;

What I want is regardless of the orientation, the textfield to have an x origin at around the center of the screen (around point 400) and I want it to maintain its distance with the right screen edge and expand its width otherwise (flexible left margin).

This works fine if I comment out the autoresizingMask line and I start the device in portrait. However, whenever I add the autoresizing line back in it moves the text field away from point 400, EVEN IN PORTRAIT.

Any suggestions? I've tried also adding the textfield to the content view, but this doesn't seem to change anything.

EDIT: I have thought about using the layoutsubviews method, but this seems kinda crude because I'd have to hard-code in a whole bunch of different coordinates. Thus, if there is another way to do this, that would be preferred.

EDIT: For example, in order to get the textfield to start around the middle I have to give it a frame xOrigin of around 150.

Upvotes: 0

Views: 859

Answers (2)

omz
omz

Reputation: 53561

You shouldn't hardcode 400 if you want to have it in the middle. Just use self.bounds.size.width * 0.5.

Not sure right now, but your second edit seems to suggest that the cell is initialized with a frame suitable for iPhone in portrait orientation by default (320 points), so 400 would be outside of the initial bounds of the view. As the text field is initially outside of the cell's bounds, it would try to keep it that way with the flexible left margin autoresizing mask.

Upvotes: 1

Jonathan Naguin
Jonathan Naguin

Reputation: 14796

You are setting wrong the autoresizingMask. You must specify the value combining the constants described in UIViewAutoresizing using the C bitwise OR operator, like:

self.myTextField.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin;

Upvotes: 1

Related Questions