【问题标题】:Having a UITextField in a UITableViewCell在 UITableViewCell 中有一个 UITextField
【发布时间】:2010-09-29 09:13:49
【问题描述】:

我现在正在尝试这样做几天,在阅读了大量尝试这样做的人的消息之后,我仍然无法在我的一些 @987654324 中拥有完全正常工作的 UITextField @,就像在这个例子中一样:

要么我的表单正常工作,但文本不可见(尽管我将其颜色设置为蓝色),当我单击它时键盘会进入该字段并且我无法正确实现键盘事件。 我尝试了一堆来自 Apple 的示例(主要是 UICatalog,其中有一个类似的控件),但它仍然无法正常工作。

有人可以帮助我(以及所有试图实现此控制的人)并在UITableViewCell 中发布UITextField 的简单实现,效果很好吗?

【问题讨论】:

  • 我已经让它工作了。但仅限于少数领域。当表中有多个字段或只有一个字段时,您是否遇到了问题?
  • 我只需要它为 2 个字段工作......它现在不工作,即使我尝试一个字段。您可以发布您的有效实施吗?谢谢PEZ!
  • 您尝试过 EditableDetailView 示例吗?在这里也写下这个问题,因为你还不能评论答案。
  • 各位朋友,可以在表格视图中添加多个文本字段stackoverflow.com/questions/19621732/…
  • 为什么网上所有的答案都归结为CGRectMake(A_MAGIC_NUMBER, ANOTHER_MAGIC_NUMBER, YET_ANOTHER_HARDCODED_MAGIC_NUMBER, OH_HERES_ANOTHER_MYSTERIOUS_HARDCODED_MAGIC_NUMBER)?这些数字从何而来?

标签: ios objective-c uitableview cocoa-touch uitextfield


【解决方案1】:

试试这个。对我来说就像一个魅力(在 iPhone 设备上)。我曾经将此代码用于登录屏幕。我将表格视图配置为有两个部分。你当然可以去掉部分条件。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:kCellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
                                   reuseIdentifier:kCellIdentifier] autorelease];
    cell.accessoryType = UITableViewCellAccessoryNone;

    if ([indexPath section] == 0) {
        UITextField *playerTextField = [[UITextField alloc] initWithFrame:CGRectMake(110, 10, 185, 30)];
        playerTextField.adjustsFontSizeToFitWidth = YES;
        playerTextField.textColor = [UIColor blackColor];
        if ([indexPath row] == 0) {
            playerTextField.placeholder = @"example@gmail.com";
            playerTextField.keyboardType = UIKeyboardTypeEmailAddress;
            playerTextField.returnKeyType = UIReturnKeyNext;
        }
        else {
            playerTextField.placeholder = @"Required";
            playerTextField.keyboardType = UIKeyboardTypeDefault;
            playerTextField.returnKeyType = UIReturnKeyDone;
            playerTextField.secureTextEntry = YES;
        }       
        playerTextField.backgroundColor = [UIColor whiteColor];
        playerTextField.autocorrectionType = UITextAutocorrectionTypeNo; // no auto correction support
        playerTextField.autocapitalizationType = UITextAutocapitalizationTypeNone; // no auto capitalization support
        playerTextField.textAlignment = UITextAlignmentLeft;
        playerTextField.tag = 0;
        //playerTextField.delegate = self;

        playerTextField.clearButtonMode = UITextFieldViewModeNever; // no clear 'x' button to the right
        [playerTextField setEnabled: YES];

        [cell.contentView addSubview:playerTextField];

        [playerTextField release];
    }
}
if ([indexPath section] == 0) { // Email & Password Section
    if ([indexPath row] == 0) { // Email
        cell.textLabel.text = @"Email";
    }
    else {
        cell.textLabel.text = @"Password";
    }
}
else { // Login button section
    cell.textLabel.text = @"Log in";
}
return cell;    
}

结果如下所示:

【讨论】:

  • 我正在尝试几乎完全相同的事情。但是,文本字段仅在选择行时显示。否则根本不绘制。在上面的例子中,我只得到了标签,即登录。这适用于 iPad 上的 iOS 4.2。
  • 其实还有一个更好的问题:你如何处理下一个/返回键盘事件?
  • @Rob:您可以通过事件获取数据。我在 editorDidEnd 事件中获取 UITextField 的内容,设置如下:[_field addTarget:self action:@selector(editingEnded:) forControlEvents:UIControlEventEditingDidEnd];.
  • 您需要将 UITextField 添加为 cell.contentView 的子视图,而不是单元格本身。
  • 使用 [cell addSubview:playerTextField]; 让它与 iOS 5.0+ 一起工作。
【解决方案2】:

这里有一个在iOS6/7/8/9下看起来不错的解决方案

2016-06-10 更新:这仍然适用于 iOS 9.3.3

感谢大家的支持,现在在 CocoaPods/Carthage/SPM 上https://github.com/fulldecent/FDTextFieldTableViewCell

基本上,我们采用UITableViewCellStyleValue1 的库存并在detailTextLabel 应该在的位置装订UITextField。这为我们提供了所有场景的自动放置:iOS6/7/8/9、iPhone/iPad、Image/No-image、Accessory/No-accessory、Portrait/Landscape、1x/2x/3x。

注意:这是使用带有名为“word”的UITableViewCellStyleValue1 类型单元格的情节提要。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell = [tableView dequeueReusableCellWithIdentifier:@"word"];
    cell.detailTextLabel.hidden = YES;
    [[cell viewWithTag:3] removeFromSuperview];
    textField = [[UITextField alloc] init];
    textField.tag = 3;
    textField.translatesAutoresizingMaskIntoConstraints = NO;
    [cell.contentView addSubview:textField];
    [cell addConstraint:[NSLayoutConstraint constraintWithItem:textField attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:cell.textLabel attribute:NSLayoutAttributeTrailing multiplier:1 constant:8]];
    [cell addConstraint:[NSLayoutConstraint constraintWithItem:textField attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:cell.contentView attribute:NSLayoutAttributeTop multiplier:1 constant:8]];
    [cell addConstraint:[NSLayoutConstraint constraintWithItem:textField attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:cell.contentView attribute:NSLayoutAttributeBottom multiplier:1 constant:-8]];
    [cell addConstraint:[NSLayoutConstraint constraintWithItem:textField attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:cell.detailTextLabel attribute:NSLayoutAttributeTrailing multiplier:1 constant:0]];
    textField.textAlignment = NSTextAlignmentRight;
    textField.delegate = self;
    return cell;
}

【讨论】:

  • 感谢您滚动浏览上面的大量选票以查看此答案!
  • UITableViewCellStyleRightDetail 是指UITableViewCellStyleValue1
  • 不幸的是,在控制台中抛出“无法同时满足约束”和文本墙。
  • 此外,如果 cell.detailTextLabel 设置为隐藏,则它根本不会对齐其右侧(“尾随”)。
  • 这与我一起使用情节提要崩溃。你可以将它与情节提要一起使用吗?
【解决方案3】:

我是这样实现的:

TextFormCell.h

#import <UIKit/UIKit.h>

#define CellTextFieldWidth 90.0
#define MarginBetweenControls 20.0

@interface TextFormCell : UITableViewCell {
 UITextField *textField;
}

@property (nonatomic, retain) UITextField *textField;

@end

TextFormCell.m

#import "TextFormCell.h"

@implementation TextFormCell

@synthesize textField;

- (id)initWithReuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithReuseIdentifier:reuseIdentifier]) {
  // Adding the text field
  textField = [[UITextField alloc] initWithFrame:CGRectZero];
  textField.clearsOnBeginEditing = NO;
  textField.textAlignment = UITextAlignmentRight;
  textField.returnKeyType = UIReturnKeyDone;
  [self.contentView addSubview:textField];
    }
    return self;
}

- (void)dealloc {
 [textField release];
    [super dealloc];
}

#pragma mark -
#pragma mark Laying out subviews

- (void)layoutSubviews {
 CGRect rect = CGRectMake(self.contentView.bounds.size.width - 5.0, 
        12.0, 
        -CellTextFieldWidth, 
        25.0);
 [textField setFrame:rect];
 CGRect rect2 = CGRectMake(MarginBetweenControls,
       12.0,
         self.contentView.bounds.size.width - CellTextFieldWidth - MarginBetweenControls,
         25.0);
 UILabel *theTextLabel = (UILabel *)[self textLabel];
 [theTextLabel setFrame:rect2];
}

它可能看起来有点冗长,但它确实有效!

别忘了设置委托!

【讨论】:

    【解决方案4】:

    这应该不难。在为表格创建单元格时,将 UITextField 对象添加到单元格的内容视图中

    UITextField *txtField = [[UITextField alloc] initWithFrame....]
    ...
    [cell.contentView addSubview:txtField]
    

    将 UITextField 的委托设置为 self(即您的视图控制器) 给文本字段一个标签,以便您可以识别在您的委托方法中编辑了哪个文本字段。当用户点击文本字段时,键盘应该会弹出。我让它像这样工作。希望对您有所帮助。

    【讨论】:

    • 我碰巧喜欢这个解决方案。如果您提前将文本字段设置为 CGRectZero 作为框架,请确保在将其添加到视图层次结构之前设置文本字段的框架。获取单元格内容视图的frame 属性尤其对此类任务很有帮助。
    • 就我而言,只需将 cell.addsubview 更改为 cell.contentView.addSubview 就可以了...
    【解决方案5】:

    试试这个。它也可以处理滚动,您可以重复使用单元格,而无需删除之前添加的子视图。

    - (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section{
        return 10;
    }   
    
    - (UITableViewCell *)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        UITableViewCell *cell = [table dequeueReusableCellWithIdentifier:@"Cell"];
        if( cell == nil)
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"] autorelease];   
    
        cell.textLabel.text = [[NSArray arrayWithObjects:@"First",@"Second",@"Third",@"Forth",@"Fifth",@"Sixth",@"Seventh",@"Eighth",@"Nineth",@"Tenth",nil] 
                               objectAtIndex:indexPath.row];
    
        if (indexPath.row % 2) {
            UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 200, 21)];
            textField.placeholder = @"Enter Text";
            textField.text = [inputTexts objectAtIndex:indexPath.row/2];
            textField.tag = indexPath.row/2;
            textField.delegate = self;
            cell.accessoryView = textField;
            [textField release];
        } else
            cell.accessoryView = nil;
    
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;        
    }
    
    - (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
        [inputTexts replaceObjectAtIndex:textField.tag withObject:textField.text];
        return YES;
    }
    
    - (void)viewDidLoad {
        inputTexts = [[NSMutableArray alloc] initWithObjects:@"",@"",@"",@"",@"",nil];
        [super viewDidLoad];
    }
    

    【讨论】:

    • 这个 sn-p 是否在某处缺少 [inputTexts 版本]?可能在viewDidUnload方法中,否则有内存泄漏。
    • 旧帖,但是...我无法使文本框的字体变小或变大。有可能吗?
    • 有人能提供一个 Swift sn-p 解决方案吗?
    【解决方案6】:

    详情

    • Xcode 10.2 (10E125)、Swift 5

    完整示例代码

    TextFieldInTableViewCell

    import UIKit
    
    protocol TextFieldInTableViewCellDelegate: class {
        func textField(editingDidBeginIn cell:TextFieldInTableViewCell)
        func textField(editingChangedInTextField newText: String, in cell: TextFieldInTableViewCell)
    }
    
    class TextFieldInTableViewCell: UITableViewCell {
    
        private(set) weak var textField: UITextField?
        private(set) weak var descriptionLabel: UILabel?
    
        weak var delegate: TextFieldInTableViewCellDelegate?
    
        override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
            super.init(style: style, reuseIdentifier: reuseIdentifier)
            setupSubviews()
        }
    
        private func setupSubviews() {
            let stackView = UIStackView()
            stackView.distribution = .fill
            stackView.alignment = .leading
            stackView.spacing = 8
            contentView.addSubview(stackView)
            stackView.translatesAutoresizingMaskIntoConstraints = false
            stackView.topAnchor.constraint(equalTo: topAnchor, constant: 6).isActive = true
            stackView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -6).isActive = true
            stackView.leftAnchor.constraint(equalTo: leftAnchor, constant: 16).isActive = true
            stackView.rightAnchor.constraint(equalTo: rightAnchor, constant: -16).isActive = true
    
            let label = UILabel()
            label.text = "Label"
            stackView.addArrangedSubview(label)
            descriptionLabel = label
    
            let textField = UITextField()
            textField.textAlignment = .left
            textField.placeholder = "enter text"
            textField.setContentHuggingPriority(.fittingSizeLevel, for: .horizontal)
            stackView.addArrangedSubview(textField)
            textField.addTarget(self, action: #selector(textFieldValueChanged(_:)), for: .editingChanged)
            textField.addTarget(self, action: #selector(editingDidBegin), for: .editingDidBegin)
            self.textField = textField
    
            stackView.layoutSubviews()
            selectionStyle = .none
    
            let gesture = UITapGestureRecognizer(target: self, action: #selector(didSelectCell))
            addGestureRecognizer(gesture)
        }
    
        required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) }
    }
    
    extension TextFieldInTableViewCell {
        @objc func didSelectCell() { textField?.becomeFirstResponder() }
        @objc func editingDidBegin() { delegate?.textField(editingDidBeginIn: self) }
        @objc func textFieldValueChanged(_ sender: UITextField) {
            if let text = sender.text { delegate?.textField(editingChangedInTextField: text, in: self) }
        }
    }
    

    视图控制器

    import UIKit
    
    class ViewController: UIViewController {
    
        private weak var tableView: UITableView?
        override func viewDidLoad() {
            super.viewDidLoad()
            setupTableView()
        }
    }
    
    extension ViewController {
    
        func setupTableView() {
    
            let tableView = UITableView(frame: .zero)
            tableView.register(TextFieldInTableViewCell.self, forCellReuseIdentifier: "TextFieldInTableViewCell")
            view.addSubview(tableView)
            tableView.translatesAutoresizingMaskIntoConstraints = false
            tableView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
            tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
            tableView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
            tableView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
            tableView.rowHeight = UITableView.automaticDimension
            tableView.estimatedRowHeight = UITableView.automaticDimension
            tableView.tableFooterView = UIView()
            self.tableView = tableView
            tableView.dataSource = self
    
            let gesture = UITapGestureRecognizer(target: tableView, action: #selector(UITextView.endEditing(_:)))
            tableView.addGestureRecognizer(gesture)
        }
    }
    
    extension ViewController: UITableViewDataSource {
    
        func numberOfSections(in tableView: UITableView) -> Int { return 1 }
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 2 }
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "TextFieldInTableViewCell") as! TextFieldInTableViewCell
            cell.delegate = self
            return cell
        }
    }
    
    extension ViewController: TextFieldInTableViewCellDelegate {
    
        func textField(editingDidBeginIn cell: TextFieldInTableViewCell) {
            if let indexPath = tableView?.indexPath(for: cell) {
                print("textfield selected in cell at \(indexPath)")
            }
        }
    
        func textField(editingChangedInTextField newText: String, in cell: TextFieldInTableViewCell) {
            if let indexPath = tableView?.indexPath(for: cell) {
                print("updated text in textfield in cell as \(indexPath), value = \"\(newText)\"")
            }
        }
    }
    

    结果

    【讨论】:

      【解决方案7】:

      我一直通过在每次出现我的单元格时调用一个方法来运行[cell.contentView bringSubviewToFront:textField] 来避免这种情况,但后来我发现了这个相对简单的技术:

      cell.accessoryView = textField;
      

      似乎没有相同的背景过度粘贴问题,并且它自己对齐(有点)。此外,textLabel 会自动截断以避免溢出到(或下)它,这很方便。

      【讨论】:

      • 我收回了.. 我不喜欢。 =(
      【解决方案8】:

      我遇到了同样的问题。似乎设置 cell.textlabel.text 属性会将 UILabel 带到单元格 contentView 的前面。 在设置 textLabel.text 后添加 textView,或者(如果不可能的话)调用这个:

      [cell.contentView bringSubviewToFront:textField]
      

      【讨论】:

        【解决方案9】:

        我在 iPad 上完成这项任务时真的很吃力,文本字段在 UITableView 中显示为不可见,并且当它获得焦点时整行变成蓝色。

        最终对我有用的是 Apple 的“静态行内容的技术”中描述的技术 Table View Programming Guide。我将标签和文本字段都放在视图的NIB 中的UITableViewCell 中,然后通过cellForRowAtIndexPath: 中的插座拉出该单元格。生成的代码比 UICatalog 整洁得多。

        【讨论】:

          【解决方案10】:

          这是我认为正确的方法。当我测试它时,它适用于 Ipad 和 Iphone。我们必须通过对 uitableviewcell 进行分类来创建自己的 customCell:

          从 interfaceBuilder 开始... 创建一个新的 UIViewcontroller 调用它 customCell (当你在那里时自愿参加 xib) 确保 customCell 是 uitableviewcell 的子类

          现在删除所有视图并创建一个视图,使其大小与单个单元格相同。使该视图成为customcell的子类。现在创建另外两个视图(复制第一个)。
          转到您的连接检查器并找到 2 个您现在可以连接到这些视图的 IBOutlets。

          -backgroundView - 选定背景

          将它们连接到您刚刚复制的最后两个视图,不用担心它们。 扩展 customCell 的第一个视图,将您的标签和 uitextfield 放入其中。 进入 customCell.h 并连接您的标签和文本字段。将此视图的高度设置为 75(每个单元格的高度) 全做完了。

          在您的 customCell.m 文件中,确保构造函数看起来像这样:

          - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
          {
          self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
          if (self) {
              // Initialization code
              NSArray *nibArray = [[NSBundle mainBundle] loadNibNamed:@"CustomCell"       owner:self options:nil]; 
              self = [nibArray objectAtIndex:0];
          }
          return self;
          }
          

          现在创建一个 UITableViewcontroller 并在此方法中使用 customCell 类,如下所示:

          - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
          {
          static NSString *CellIdentifier = @"Cell";
          // lets use our customCell which has a label and textfield already installed for us
          
          customCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
          if (cell == nil) {
              //cell = [[[customCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
          
          
              NSArray *topLevelsObjects = [[NSBundle mainBundle] loadNibNamed:@"NewUserCustomCell" owner:nil options:nil];
              for (id currentObject in topLevelsObjects){
                  if ([currentObject  isKindOfClass:[UITableViewCell class]]){
                      cell = (customCell *) currentObject;
                      break;
                  }
              }
          
              NSUInteger row = [indexPath row];
          
          switch (row) {
              case 0:
              {
          
                  cell.titleLabel.text = @"First Name"; //label we made (uitextfield also available now)
          
                  break;
              }
          
          
                  }
          return cell;
          

          }

          - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
          
          return 75.0;
          }
          

          【讨论】:

            【解决方案11】:

            这是UITableViewCell 的插入子类,它用可编辑的UITextField 替换了detailTextLabel(或者,如果是UITableViewCellStyleDefault,则替换textLabel )。这样做的好处是它允许你重用所有熟悉的 UITableViewCellStyles、accessoryViews 等,现在细节是可编辑的!

            @interface GSBEditableTableViewCell : UITableViewCell <UITextFieldDelegate>
            @property UITextField *textField;
            @end
            
            @interface GSBEditableTableViewCell ()
            @property UILabel *replace;
            @end
            
            @implementation GSBEditableTableViewCell
            
            - (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
            {
                self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
                if (self) {
                    _replace = (style == UITableViewCellStyleDefault)? self.textLabel : self.detailTextLabel;
                    _replace.hidden = YES;
            
                    // Impersonate UILabel with an identical UITextField
                    _textField = UITextField.new;
                    [self.contentView addSubview:_textField];
                    _textField.translatesAutoresizingMaskIntoConstraints = NO;
                    [_textField.leftAnchor constraintEqualToAnchor:_replace.leftAnchor].active = YES;
                    [_textField.rightAnchor constraintEqualToAnchor:_replace.rightAnchor].active = YES;
                    [_textField.topAnchor constraintEqualToAnchor:_replace.topAnchor].active = YES;
                    [_textField.bottomAnchor constraintEqualToAnchor:_replace.bottomAnchor].active = YES;
                    _textField.font = _replace.font;
                    _textField.textColor = _replace.textColor;
                    _textField.textAlignment = _replace.textAlignment;
            
                    // Dont want to intercept UITextFieldDelegate, so use UITextFieldTextDidChangeNotification instead
                    [NSNotificationCenter.defaultCenter addObserver:self
                                                       selector:@selector(textDidChange:)
                                                           name:UITextFieldTextDidChangeNotification
                                                         object:_textField];
            
                    // Also need KVO because UITextFieldTextDidChangeNotification not fired when change programmatically
                    [_textField addObserver:self forKeyPath:@"text" options:0 context:nil];
                }
                return self;
            }
            
            - (void)textDidChange:(NSNotification*)notification
            {
                // Update (hidden) UILabel to ensure correct layout
                if (_textField.text.length) {
                    _replace.text = _textField.text;
                } else if (_textField.placeholder.length) {
                    _replace.text = _textField.placeholder;
                } else {
                    _replace.text = @" "; // otherwise UILabel removed from cell (!?)
                }
                [self setNeedsLayout];
            }
            
            - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
            {
                if ((object == _textField) && [keyPath isEqualToString:@"text"]) [self textDidChange:nil];
            }
            
            - (void)dealloc
            {
                [_textField removeObserver:self forKeyPath:@"text"];
            }
            
            @end
            

            使用简单 - 只需像以前一样创建单元格,但现在使用 cell.textField 而不是 cell.detailTextLabel(或 cell.textLabel > 如果是UITableViewCellStyleDefault)。例如

            GSBEditableTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
            if (!cell) cell = [GSBEditableTableViewCell.alloc initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:@"Cell"];
            
            cell.textLabel.text = @"Name";
            cell.textField.text = _editablename;
            cell.textField.delegate = self; // to pickup edits
            ...
            

            受 FD 的回答启发和改进

            【讨论】:

              【解决方案12】:

              对于此方法中 UITableViewCell 内多个 UITextfield 上的下一个/返回事件,我在 storyboard 中采用了 UITextField。

              @interface MyViewController () {
                  NSInteger currentTxtRow;
              }
              @end
              @property (strong, nonatomic) NSIndexPath   *currentIndex;//Current Selected Row
              
              @implementation MyViewController
              
              
              - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
              
                      UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CELL" forIndexPath:indexPath];
                      cell.selectionStyle = UITableViewCellSelectionStyleNone;
              
                      UITextField *txtDetails = (UITextField *)[cell.contentView viewWithTag:100];
                      txtDetails.delegate = self;
              
                      txtDetails.placeholder = self.arrReciversDetails[indexPath.row];
                      return cell;
              }
              
              
              #pragma mark - UITextFieldDelegate
              - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
              
                  CGPoint point = [textField convertPoint:CGPointZero toView:self.tableView];
                  self.currentIndex = [self.tableView indexPathForRowAtPoint:point];//Get Current UITableView row
                  currentTxtRow = self.currentIndex.row;
                  return YES;
              }
              
              
              - (BOOL)textFieldShouldReturn:(UITextField *)textField {
                  currentTxtRow += 1;
                  self.currentIndex = [NSIndexPath indexPathForRow:currentTxtRow inSection:0];
              
                  UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:self.currentIndex];
                  UITextField *currentTxtfield = (UITextField *)[cell.contentView viewWithTag:100];
                  if (currentTxtRow < 3) {//Currently I have 3 Cells each cell have 1 UITextfield
                      [currentTxtfield becomeFirstResponder];
                  } else {
                      [self.view endEditing:YES];
                      [currentTxtfield resignFirstResponder];
                  }
              
              }  
              

              从文本字段中获取文本-

              - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
                    switch (self.currentIndex.row) {
              
                          case 0:
                              NSLog(@"%@",[NSString stringWithFormat:@"%@%@",textField.text,string]);//Take current word and previous text from textfield
                              break;
              
                          case 1:
                               NSLog(@"%@",[NSString stringWithFormat:@"%@%@",textField.text,string]);//Take current word and previous text from textfield
                              break;
              
                          case 2:
                               NSLog(@"%@",[NSString stringWithFormat:@"%@%@",textField.text,string]);//Take current word and previous text from textfield
                              break;
              
                          default:
                              break;
                      }
              }
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 2011-09-19
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多