在UITableViewCell中有一个UITextField

我试图做了几天,现在读了大量的人尝试这样做的消息后,我仍然无法在我的一些UITableViewCells有一个完整的工作UITextField ,就像在这个例子:

截图

或者我有窗体的工作,但文本是不可见的(虽然我把它的颜色设置为蓝色),当我点击键盘时,键盘会出现在字段上,我无法正确实现键盘事件。 我尝试了一堆苹果的例子(主要是UICatalog ,那里有一个类似的控制),但它仍然不能正常工作。

有人可以帮助我(和所有的人试图实现这个控制),并发布在UITableViewCellUITextField的简单实现,这工作正常吗?

试试这个。 对我来说就像一个魅力(在iPhone设备上)。 我曾经使用这个代码的login屏幕。 我configuration了表格视图有两个部分。 你当然可以摆脱部分条件。

 - (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; } 

结果如下所示:

登录表单

这是一个在iOS6 / 7/8/9下看起来不错的解决scheme

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

感谢所有的支持,现在在CocoaPods / Carthage / SPM上, url是https://github.com/fulldecent/FDTextFieldTableViewCell

基本上我们拿着股票UITableViewCellStyleValue1detailTextLabel所在的UITextField 。 这使我们可以自动放置所有场景:iOS6 / 7/8/9,iPhone / iPad,图像/无图像,附件/无配件,纵向/横向,1x / 2x / 3x。

在这里输入图像描述

注意:这是使用一个名为“word”的UITableViewCellStyleValue1types的单元格的故事板。

 - (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; } 

以下是我如何实现这一点:

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]; } 

它可能看起来有点冗长,但是起作用了!

不要忘记设置代表!

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

 - (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]; } 

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

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

将UITextField的委托设置为self(即您的viewcontroller)给文本字段添加一个标签,以便您可以确定在委托方法中编辑了哪个文本字段。 当用户点击文本字段时,键盘应该popup。 我是这样工作的 希望它有帮助。

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

 cell.accessoryView = textField; 

似乎没有相同的背景问题,而且它本身(有点)是一致的。 此外,textLabel自动截断,以避免溢出(或低于),这是很方便的。

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

 [cell.contentView bringSubviewToFront:textField] 

我真的很难在iPad上完成这个任务,在UITableView中显示的文本字段不可见,整个行在焦点时变成蓝色。

苹果桌面视图编程指南中的 “静态行内容技术”中描述的技术最终适用于我。 我把标签和textField都放在NIB视图的UITableViewCell中,然后通过cellForRowAtIndexPath:的出口拉出这个单元。 由此产生的代码比UICatalog更加整洁。

UITableViewCell中的UITextField在Swift 3中

细节

Xcode 8.2.1,Swift 3

任务

在UITableViewCell中创buildUITextField并将UITextField编辑function委托给ViewController

完整的示例代码

类ViewController

 import UIKit class ViewController: UIViewController { @IBOutlet var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() setupTableView() } } // MARK: - TableView extension ViewController { func setupTableView() { tableView.dataSource = self tableView.tableFooterView = UIView() let gesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.endEditing)) tableView.addGestureRecognizer(gesture) } func endEditing() { tableView.endEditing(true) } } // MARK: - UITableViewDataSource 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 } } // MARK: - TextFieldInTableViewCellDelegate extension ViewController: TextFieldInTableViewCellDelegate { func textFieldInTableViewCell(didSelect cell:TextFieldInTableViewCell) { if let indexPath = tableView.indexPath(for: cell){ print("didSelect cell: \(indexPath)") } } func textFieldInTableViewCell(cell:TextFieldInTableViewCell, editingChangedInTextField newText:String) { if let indexPath = tableView.indexPath(for: cell){ print("editingChangedInTextField: \"\(newText)\" in cell: \(indexPath)") } } } 

类TextFieldInTableViewCell

 import UIKit class TextFieldInTableViewCell: UITableViewCell { @IBOutlet var textField: UITextField! @IBOutlet var descriptionLabel: UILabel! var delegate: TextFieldInTableViewCellDelegate? override func awakeFromNib() { super.awakeFromNib() let gesture = UITapGestureRecognizer(target: self, action: #selector(TextFieldInTableViewCell.didSelectCell)) addGestureRecognizer(gesture) } } // MARK: - Actions extension TextFieldInTableViewCell { func didSelectCell() { textField.becomeFirstResponder() delegate?.textFieldInTableViewCell(didSelect: self) } @IBAction func textFieldValueChanged(_ sender: UITextField) { if let text = sender.text { delegate?.textFieldInTableViewCell(cell: self, editingChangedInTextField: text) } } } 

协议TextFieldInTableViewCellDelegate

 import UIKit protocol TextFieldInTableViewCellDelegate { func textFieldInTableViewCell(didSelect cell:TextFieldInTableViewCell) func textFieldInTableViewCell(cell:TextFieldInTableViewCell, editingChangedInTextField newText:String) } 

Main.storyboard

 <?xml version="1.0" encoding="UTF-8"?> <document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="11762" systemVersion="16C67" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="BYZ-38-t0r"> <device id="retina4_7" orientation="portrait"> <adaptation id="fullscreen"/> </device> <dependencies> <deployment identifier="iOS"/> <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="11757"/> <capability name="Constraints to layout margins" minToolsVersion="6.0"/> <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> </dependencies> <scenes> <!--View Controller--> <scene sceneID="tne-QT-ifu"> <objects> <viewController id="BYZ-38-t0r" customClass="ViewController" customModule="stackoverflow_409259" customModuleProvider="target" sceneMemberID="viewController"> <layoutGuides> <viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/> <viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/> </layoutGuides> <view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC"> <rect key="frame" x="0.0" y="0.0" width="375" height="667"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <subviews> <tableView clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="44" sectionHeaderHeight="28" sectionFooterHeight="28" translatesAutoresizingMaskIntoConstraints="NO" id="2cP-ct-Jtg"> <rect key="frame" x="0.0" y="20" width="375" height="647"/> <color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/> <prototypes> <tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="none" indentationWidth="10" reuseIdentifier="TextFieldInTableViewCell" id="KnN-sc-zHs" customClass="TextFieldInTableViewCell" customModule="stackoverflow_409259" customModuleProvider="target"> <rect key="frame" x="0.0" y="28" width="375" height="44"/> <autoresizingMask key="autoresizingMask"/> <tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="KnN-sc-zHs" id="AK1-Th-ke8"> <rect key="frame" x="0.0" y="0.0" width="375" height="43"/> <autoresizingMask key="autoresizingMask"/> <subviews> <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Label" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="pEG-c7-yoZ"> <rect key="frame" x="8" y="11" width="77" height="21"/> <constraints> <constraint firstAttribute="width" constant="77" id="zhu-LA-GOo"/> </constraints> <fontDescription key="fontDescription" type="system" pointSize="14"/> <nil key="textColor"/> <nil key="highlightedColor"/> </label> <textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" contentHorizontalAlignment="left" contentVerticalAlignment="center" placeholder="text" textAlignment="natural" minimumFontSize="17" translatesAutoresizingMaskIntoConstraints="NO" id="O1l-cp-c2b"> <rect key="frame" x="93" y="6" width="256" height="31"/> <nil key="textColor"/> <fontDescription key="fontDescription" type="system" pointSize="14"/> <textInputTraits key="textInputTraits"/> <connections> <action selector="textFieldValueChanged:" destination="KnN-sc-zHs" eventType="editingChanged" id="0KD-Yx-Cl0"/> </connections> </textField> </subviews> <constraints> <constraint firstItem="O1l-cp-c2b" firstAttribute="leading" secondItem="pEG-c7-yoZ" secondAttribute="trailing" constant="8" symbolic="YES" id="4bh-3C-WXp"/> <constraint firstItem="pEG-c7-yoZ" firstAttribute="centerY" secondItem="O1l-cp-c2b" secondAttribute="centerY" id="A0b-Mk-8KQ"/> <constraint firstItem="O1l-cp-c2b" firstAttribute="top" secondItem="AK1-Th-ke8" secondAttribute="topMargin" constant="-2" id="BDA-fk-4JI"/> <constraint firstAttribute="trailingMargin" secondItem="O1l-cp-c2b" secondAttribute="trailing" constant="18" id="bYA-UQ-iBv"/> <constraint firstItem="pEG-c7-yoZ" firstAttribute="top" secondItem="AK1-Th-ke8" secondAttribute="topMargin" constant="3" id="eDx-qb-b2G"/> <constraint firstItem="pEG-c7-yoZ" firstAttribute="leading" secondItem="AK1-Th-ke8" secondAttribute="leadingMargin" id="tpb-h3-LVs"/> <constraint firstItem="pEG-c7-yoZ" firstAttribute="centerY" secondItem="AK1-Th-ke8" secondAttribute="centerY" id="vsl-oj-yAN"/> </constraints> </tableViewCellContentView> <connections> <outlet property="descriptionLabel" destination="pEG-c7-yoZ" id="qdF-mm-xgu"/> <outlet property="textField" destination="O1l-cp-c2b" id="WMb-QW-wLg"/> </connections> </tableViewCell> </prototypes> </tableView> </subviews> <color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/> <constraints> <constraint firstItem="2cP-ct-Jtg" firstAttribute="leading" secondItem="8bC-Xf-vdC" secondAttribute="leading" id="8M7-lY-IPn"/> <constraint firstItem="2cP-ct-Jtg" firstAttribute="bottom" secondItem="wfy-db-euE" secondAttribute="top" id="GaT-6q-zdl"/> <constraint firstAttribute="trailing" secondItem="2cP-ct-Jtg" secondAttribute="trailing" id="pSM-zU-ndL"/> <constraint firstItem="2cP-ct-Jtg" firstAttribute="top" secondItem="y3c-jy-aDJ" secondAttribute="bottom" id="tkS-4A-t2B"/> </constraints> </view> <connections> <outlet property="tableView" destination="2cP-ct-Jtg" id="VSj-8p-8c0"/> </connections> </viewController> <placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/> </objects> <point key="canvasLocation" x="-79.200000000000003" y="138.98050974512745"/> </scene> </scenes> </document> 

结果

在这里输入图像描述 在这里输入图像描述

这是如何做的,我相信正确的方法。 它适用于Ipad和Iphone,因为我testing了它。 我们必须通过分类一个可用的viewcell来创build我们自己的customCells:

在interfaceBuilder中开始…创build一个新的UIViewcontroller将其称为customCell(当你在那里时为xib做志愿者)确保customCell是uitableviewcell的一个子类

现在清除所有视图,并创build一个视图,使其成为单个单元格的大小。 使该视图子类customcell。 现在创build另外两个视图(重复第一个)。
去你的连接督察,find2个IBOutlets,你可以连接到这些意见现在。

-backgroundView -SelectedBackground

把这些连接到刚刚复制的最后两个视图,不用担心。 扩展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; } 

现在创build一个UITableView控制器,在这个方法中使用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; } 

这是UITableViewCell的一个embedded子类,它用一个可编辑的UITextFieldreplace了detailTextLabel (或者在UITableViewCellStyleDefault情况下replace了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 

简单易用 – 只需像以前一样创build单元格,但是现在使用cell.textField而不是cell.detailTextLabel (或者在UITableViewCellStyleDefault情况下使用cell.textLabel )。 例如

 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的答复的启发和改进

对于这个方法中的UITableViewCell中的多个UITextfield上的下一个/返回事件,我在故事板中使用了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]; } } 

要从textfield获取文本 –

 - (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; } }