Jon*_*ens 34 uitableview tableview swift xcode6 ios8
所以我想获取我选择的行的textLabel的值.我试过打印它,但它没有用.经过一些研究,我发现这段代码有效,但仅限于Objective-C;
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"did select and the text is %@",[tableView cellForRowAtIndexPath:indexPath].textLabel.text);]
}
Run Code Online (Sandbox Code Playgroud)
我找不到Swift的任何解决方案.虽然打印indexpath.row是可能的,但这不是我需要的.
所以我该怎么做?或者这段代码的"Swift版本"是什么?
der*_*ida 122
试试这个:
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let indexPath = tableView.indexPathForSelectedRow() //optional, to get from any UIButton for example
let currentCell = tableView.cellForRowAtIndexPath(indexPath) as UITableViewCell
print(currentCell.textLabel!.text)
Run Code Online (Sandbox Code Playgroud)
Ant*_*nio 13
如果你是一个继承自的类UITableViewController,那么这就是swift版本:
override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
let cell = self.tableView.cellForRowAtIndexPath(indexPath)
NSLog("did select and the text is \(cell?.textLabel?.text)")
}
Run Code Online (Sandbox Code Playgroud)
请注意,这cell是一个可选项,因此必须将其解包 - 并且相同textLabel.如果2中的任何一个为nil(不太可能发生,因为使用有效的索引路径调用该方法),如果要确保打印有效值,则应检查两者cell并且textLabel都不是nil:
override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
let cell = self.tableView.cellForRowAtIndexPath(indexPath)
let text = cell?.textLabel?.text
if let text = text {
NSLog("did select and the text is \(text)")
}
}
Run Code Online (Sandbox Code Playgroud)
斯威夫特4
获取所选行的标签:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! TableViewCell
print(cell.textLabel?.text)
}
Run Code Online (Sandbox Code Playgroud)
要获取取消选择的行的标签:
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! TableViewCell
print(cell.textLabel?.text)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
103123 次 |
| 最近记录: |