使用Swift编程以编程方式设置文本框的占位符。

4

我目前正在研究如何设置文本字段的占位符文本。该文本字段位于单元格中。我想分配给占位符的文本包含在数组中。

以前我曾尝试设置图像,代码如下:

cell?.imageView?.image = row1images[indexPath.row]

因此,我认为使用这种思想,可以使用...
cell?.textField?.text = nil
cell?.textField?.placeholder = row1[indexPath.row]

...会起作用。然而,我收到了错误提示:“UITableViewCell的类型没有成员'textField'”


1
UITableViewCell 没有文本字段,因此出现错误。也许 cell 应该声明为您自定义单元格的实际类型。 - rmaddy
你创建过自定义单元格吗?展示一下cellforrowatindexpath的完整代码。 - RajeshKumar R
你有两种选项来设置TextField的占位符: TextField PlaceHolder - Kirit Modi
2个回答

1

请尝试以下内容...

如果您的自定义单元格中有一个textField,请在cellForRowAt函数中添加以下代码。

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

            let cell = tableView.dequeueReusableCell(withIdentifier: "CustomTableViewCell", for: indexPath) as! CustomTableViewCell

            cell .yourTextField.attributedPlaceholder = NSAttributedString(string: row1[indexPath.row],
                                                                       attributes: [NSForegroundColorAttributeName: UIColor.black])


            return cell
    }

我收到一个错误,错误信息为“使用未声明的类型“CustomTableViewCell”。 - Michela

0
错误信息"Value of type ‘UITableViewCell’ has no member 'textField'"已经说明了问题。要么你使用了一个不知道你的TextFieldprototype cell,要么你使用了你的custom cell但是没有将它的类更改为你的CustomCellClass。此外,你可能将你的可重用单元格强制转换为UITableViewCell而不是你的CustomCellClass
解决这些问题,你的代码就没问题了。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接