【问题标题】:IOS drop down with UITextField and UITableViewIOS下拉与UITextField和UITableView
【发布时间】:2013-08-07 13:14:08
【问题描述】:

我使用 UITextField 和 UITableView 创建了一个下拉菜单。当用户选择文本字段时,表格视图将显示为下拉列表。我已经在另一个类中设置了 tableview 委托和数据源。

现在我的问题是我想将 tableview 中选定行的文本放到文本字段上,即当用户在 tableview 中选择一行时,我想将 tableview 行文本发送回视图控制器(由文本字段组成)。

提前致谢。

【问题讨论】:

  • 你为什么不自己创建一个委托?
  • 你的意思是代替 tableview 委托创建其他自定义委托?
  • 不不,创建一个单独的委托,将选定的行文本传递回包含您的文本字段的 VC。
  • 或者只是将 VC 引用传递给 tableview 委托实例,并在选择行时调用在 VC 类中实现的适当方法
  • @Amar 感谢您的快速回复。

标签: ios uitableview drop-down-menu uitextfield


【解决方案1】:

在视图中添加下面的代码确实加载了您在其中添加了 UITextField 的类

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addValueToTextField:) name:@"addValueToTextFiel" object:nil]; 

-(void)addValueToTextField:(NSNotification *) notification{
      NSString* text = [notification text];

       yourTextField.text = text;
}

在其他类的 UITable 视图的 Didselect 委托中,您必须添加以下代码

 UITableViewCell *selectedCell =[tableView cellForRowAtIndexPath:indexPath];

 [[NSNotificationCenter defaultCenter] postNotificationName:@"addValueToTextField" object:nil userInfo:selectedCell.Text];

或者你可以使用自定义委托

【讨论】:

    【解决方案2】:

    使用 UITableView 为控制器创建自定义委托

    ItemsList .h 文件

    @protocol ItemsListDelegate : NSObject
    @optional
    - (void)itemSelected:(int)num withTitle:(NSString *)title;
    @end
    
    @interface ItemsList : UITableViewController{
    id <ItemsListDelegate> delegate;
    ...
    }
    

    ItemsList .m 文件

    #import "ItemsList.h"
    
    @implementation ItemsList<UITableViewDataSource, UITableViewDelegate>
    @synthesize delegate;
    
    .....
    
    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [delegate itemsSelected:[indexPath row] withTitle:[items objectAtIndex:[indexPath row]]];
    }
    
    .....
    

    在 ViewController 中,您的字段设置在 .h 中

    #import "ItemsList.h"
    
    @interface ViewWithField<ItemsListDelegate>{
    ItemsList *itemsList;
    }
    
    ....
    

    在.m文件中

    .....
    
    - (void)viewDidLoad
    {
        itemList.delegate = self;
    }
    
    - (void)itemSelected:(int)num withTitle:(NSString *)title{
        self.textField.text = title;
    }
    ..... 
    

    类似的东西。我不检查此代码中的错误。但是这样看。 或者使用NotificationCenter,不过这种方式更正确。

    对不起,我的英语很糟糕。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-06
      • 2011-09-11
      相关资源
      最近更新 更多