将子视图添加到自定义 class

Add subview to a custom class

我有一个 UITextField,我想在其上创建自定义 class。所以我创建了一个包含 UITextField 的 subclass 的文件。接下来,在自定义class中,我要实现一个tableView。有点像自动完成 textField.

我开始创建它,并像这样添加了 tableView

[self addSubview:self.tableView];

当我运行应用程序时,tableViewtextField中,所以我只能看到tableView的一部分。如何将其添加为 subview 以便我可以看到完整的 tableView?

这就是您要找的 https://github.com/gaurvw/MPGTextField

这个 uitextfield 子类可以满足您的需求 - 它是为 'search' 功能构建的。 如果你还想用自己的, 不将 tableview 添加到 uitextfield 本身,而是像

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

编辑:

您可以将框架设置为:

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

将子视图添加到 uitextfield 的方法是重载 layoutSubviews 方法并在那里初始化你的 tableview:

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

这会将 tableView 添加为 textField 的子视图。

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

不过,更好的办法是让tableView作为textField的superView的subView,即textFieldtableView应该是兄弟.