简体   繁体   中英

Add subview to a custom class

I have a UITextField that I want to create a custom class on. So I created a file with a subclass of UITextField . Next, in the custom class, I want to implement a tableView . Kind of like a auto-complete textField .

I started creating it, and added the tableView like this:

[self addSubview:self.tableView];

When I run the app, the tableView is in the textField , so I can only see part of the tableView . How can I add it as a subview so I can see the full tableView ?

This is what you are looking for https://github.com/gaurvw/MPGTextField

This uitextfield subclass does what you want - it's builed for 'search' feature. If you still want to use your own, add tableview not to uitextfield itself, but like

[[self superview] addSubview:tableViewController.tableView];

EDIT:

you can set frame as:

 CGRect frameForPresentation = [self frame];
 frameForPresentation.origin.y += self.frame.size.height;
 frameForPresentation.size.height = 200;
 [tableViewController.tableView setFrame:frameForPresentation];

The way to add subview to uitextfield is to overload layoutSubviews method and init your tableview there:

- (void)layoutSubviews 
{ 
[super layoutSubviews]; 
if (!self.tableview.superview) 
{ 
[self setupView]; 
} 
}

This will add the tableView as the subView of the textField .

self.tableView.frame = CGRectMake(0, CGRectGetHeight(self.bounds), CGRectGetWidth(self.bounds), YOUR_TABLE_HEIGHT);
[self addSubview:self.tableView];
self.clipsToBounds = NO;

However, a better way is to make the tableView as the textField 's superView's subView, that is, the textField and the tableView should be siblings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM