add textfield to tableviewheader

≡放荡痞女 提交于 2019-12-11 04:42:48

问题


I am trying to add textfield to header view. I could not figure out why I can't see my textfield. When I use a label it works perfectly.

Following is the code:

-(UIView*) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
       UIView *tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(40, 0, self.view.frame.size.width - 70, 30)];
    UITextField *sectionTitleTF1 = [[UITextField alloc] initWithFrame:CGRectMake(58, 0, 500, 30)];
    sectionTitleTF1.backgroundColor = [UIColor whiteColor];
    [sectionTitleTF1 becomeFirstResponder];
    [tableHeaderView addSubview:sectionTitleTF1];
return tableHeaderView;

}

Thanks


回答1:


Try this,

  You can adjust view, textfield frame based on your device ipad or iphone




 - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
return 30.0;
}

-(UIView*) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
UIView *tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(40, 0, self.view.frame.size.width - 70, 30)];
tableHeaderView.backgroundColor =[UIColor grayColor];
UITextField *sectionTitleTF1 = [[UITextField alloc] initWithFrame:CGRectMake(58, 0, 500, 30)];
sectionTitleTF1.backgroundColor = [UIColor whiteColor];
[sectionTitleTF1 setBackgroundColor:[UIColor whiteColor]];
[sectionTitleTF1 setFont:[UIFont boldSystemFontOfSize:15]];
[sectionTitleTF1 setBorderStyle:UITextBorderStyleLine];
[sectionTitleTF1 setTextAlignment:UITextAlignmentCenter];
[sectionTitleTF1 setKeyboardType:UIKeyboardTypeNumbersAndPunctuation];
[sectionTitleTF1 becomeFirstResponder];
[tableHeaderView addSubview:sectionTitleTF1];
return tableHeaderView;
}



回答2:


Have you implemented this method of the datasource? It is a must if you want your section header to show. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 30.0;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

Also, if you are unaware, you can return the UITextField directly rather than adding as a subview. However you may want it as a subview, depending on what you want to achieve.

EDIT: Datasource not Delegate




回答3:


just add this sectionTitleTF1.borderStyle = UITextBorderStyleRoundedRect; then you will see it



来源:https://stackoverflow.com/questions/15034630/add-textfield-to-tableviewheader

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!