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

Change button title based on text in tableview

我正在尝试根据表格视图中的文本选择更改按钮标题,但不知何故错误 "invalid escape sequence in literal" 总是弹出 up.can 有人帮我解决这个问题吗?谢谢!!

下面是我的代码:

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)
}

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

\(value)

所以替换这个

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

有了这个

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

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

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

对于你的情况 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 - 字符串插值部分。