根据表格视图中的文本更改按钮标题

时间:2018-11-13 15:22:25

标签: ios swift uitableview swift4.2

我试图根据表视图中的文本选择来更改按钮标题,但是总会弹出“文字中无效的转义序列”错误。有人可以帮助我解决此问题吗?谢谢!

下面是我的代码:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    cell.textLabel?.text = userList[indexPath.row]
    return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    btnDrop.setTitle("\|userList[indexPath.row|", for: .normal)
    animate(toogle: false)
}

2 个答案:

答案 0 :(得分:0)

如果要将任何可打印的值添加到字符串,则可以使用字符串插值:

\(value)

所以替换掉这个

btnDrop.setTitle("\|userList[indexPath.row|", for: .normal)

与此

btnDrop.setTitle("\(userList[indexPath.row])", for: .normal)

但是在您的情况下,您不必使用它,因为您的userList只是字符串值的数组,因此您可以简单地使用它:

btnDrop.setTitle(userList[indexPath.row], for: .normal)

答案 1 :(得分:0)

对于您的情况AuthorizationCodeWithProofKey包含字符串,这意味着不需要进行字符串插值。您可以直接使用它:

userList

但是,错误的原因是:在进行字符串插值时,您应该这样做:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    btnDrop.setTitle(userList[indexPath.row], for: .normal)
    animate(toogle: false)
}

代替:

"\(userList[indexPath.row)"

"\|userList[indexPath.row|" 而不是()

有关更多信息,请检查Swift Programming Language: Strings and Characters-字符串插值部分。