UITableViewCell не показывает detailTextLabel.text - Swift
Текст детали (субтитров) не отображается. Однако данные доступны, потому что, когда добавлен вызов println(), он печатает Необязательные ( "данные" ) на консоли с ожидаемыми данными. В раскадровке UITableViewController настроен на соответствующий класс, стиль Cell View Table - "Subtitle", а идентификатор повторного использования - "ячейка". Как я могу отобразить информацию о субтитрах?
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell
dispatch_async(dispatch_get_main_queue(), { () -> Void in
cell.textLabel.text = self.myArray[indexPath.row]["title"] as? String
cell.detailTextLabel?.text = self.myArray[indexPath.row]["subtitle"] as? String
println(self.myArray[indexPath.row]["subtitle"] as? String)
// The expected data appear in the console, but not in the iOS simulator table view cell.
})
return cell
}
Ответы
Ответ 1
Та же проблема здесь (из того, что я читал, возможно, ошибка в iOS 8?), Вот как мы работали над этим:
Удалить прототип ячейки из раскадровки
Удалить эту строку:
var cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell
- Замените на эти строки кода:
let cellIdentifier = "Cell"
var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? UITableViewCell
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.Value2, reuseIdentifier: cellIdentifier)
}
Обновление для Swift 3.1
let cellIdentifier = "Cell"
var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.value2, reuseIdentifier: cellIdentifier)
}
Обновление для Swift 4.2 - упрощенный
let cell = UITableViewCell(style: UITableViewCell.CellStyle.value2, reuseIdentifier: "cellId")
Ответ 2
Ваш код выглядит отлично. Просто перейдите в раскадровку и выберите ячейку своего стола → Теперь перейдите в Attributes Inspector и выберите стиль для Subtitle.
Следуйте этому в соответствии с приведенным ниже снимком экрана.
![Изменить эту опцию]()
Надеюсь, что это помогло.
Ответ 3
Если вы все еще хотите использовать ячейку прототипа из раскадровки, выберите стиль TableViewcell как Subtitle. он будет работать.
Ответ 4
Если делать это программно без ячеек в построителе интерфейса, этот код работает как шарм в Swift 2.0 +
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
yourTableView.delegate = self
yourTableView.dataSource = self
yourTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "subtitleCell")
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return yourTableViewArray.count
}
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
let cell: UITableViewCell = yourTableView.dequeueReusableCellWithIdentifier("subtitleCell", forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = "the text you want on main title"
cell.detailTextLabel?.text = "the text you want on subtitle"
return cell
}
Ответ 5
![enter image description here]()
Попробуйте это у меня (swift 5)
let cell = UITableViewCell(style: .value1, reuseIdentifier: "cellId")
cell.textLabel.text = "Déconnexion"
cell.imageView.image = UIImage(named: "imageName")
Цель c:
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cellId"];
Ответ 6
Если вы настроите текст на нуль где-нибудь, когда вы пытаетесь установить его на значение, отличное от нуля, фактическое представление, содержащее текст, будет отсутствовать. Это было введено в iOS8. Вместо этого попробуйте установить вместо этого пробел @" "
.
Смотрите следующее: Субтитры UITableViewCell не будут обновляться
Ответ 7
Для чего это стоит: у меня была проблема детализации, не появляющаяся. Это потому, что я зарегистрировал ячейку tableView, чего не следовало делать, поскольку прототип ячейки был определен непосредственно в раскадровке.
Ответ 8
Вот как это работает для swift 5, чтобы получить субтитры, используя detailtextlabel, используя объект UITableView в контроллере представления, если вы пропустите какой-либо из них, он не будет работать и, вероятно, потерпит крах.
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource
В viewDidLoad:
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "subtitleCell")
Функция делегата:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Fetch a cell of the appropriate type.
let cell = UITableViewCell(style: .subtitle , reuseIdentifier: "subtitleCell")
// Configure the cells contents.
cell.textLabel!.text = "Main Cell Text"
cell.detailTextLabel?.text = "Detail Cell Text"
return cell
}