【发布时间】:2020-07-06 13:50:25
【问题描述】:
我有一个静态 UITableView,我在情节提要中制作的每个单元格的内容,但我需要在运行时以编程方式更改某些单元格的 texLabels。我该怎么做?
【问题讨论】:
标签: ios objective-c uitableview
我有一个静态 UITableView,我在情节提要中制作的每个单元格的内容,但我需要在运行时以编程方式更改某些单元格的 texLabels。我该怎么做?
【问题讨论】:
标签: ios objective-c uitableview
为您要在表格视图控制器中更改的每个单元格创建一个属性,如下所示:
@property (weak) IBOutlet UITableViewCell *cell1;
@property (weak) IBOutlet UITableViewCell *cell2;
将每一个连接到 Interface Builder 中的一个单元格。
当你只需要改变标签的文字时,你可以使用
self.cell1.textLabel.text = @"New Text";
如果需要替换整个标签,请使用
UILabel *newLabel = [[UILabel alloc] init];
self.cell2.textLabel = newLabel;
【讨论】:
@RossPenman 发布了一个很好的答案。
@ggrana 指出了与内存和单元重用有关的潜在问题,不过不用担心 ...
对于带有静态单元格的UITableView,所有单元格都在前面实例化,然后在UITableViewController 上调用viewDidLoad,并且不会像动态单元格那样重用。因此,您甚至可以将IBOutlets 直接带到UITextFields、UISwitches、UILabels 以及您真正感兴趣的内容,您已将它们放入故事板中的静态单元格中。
【讨论】:
IBOutlets。我猜必须深入研究文档。
我需要这个。
dispatch_async(dispatch_get_main_queue(), ^{
(...textLabel updates)
[self.tableView reloadData];
});
【讨论】:
您可以使用 cellForRowAtIndexPath 方法从表格视图中获取单元格,您需要定义一个插座来检索您的表格视图。
__weak IBOutlet UITableView *tableView;
之后你可以得到这样的单元格:
NSIndexPath* indexPath = [NSIndexPath indexPathForRow:yourRow inSection:yourSection];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
[[cell textLabel] setText:@"Your new text"];
也许在设置文本后,您需要调整标签或单元格高度,如果您需要更深入的帮助,请提供更多信息,我很乐意为您提供帮助。
你已经完成了,希望它有所帮助。
【讨论】:
Swift 解决方案:
首先制作一个静态TableViewCell的IBOutlet
@IBOutlet weak var cellFirst: UITableViewCell!
然后在 viewDidLoad 中更改标签名称。
cellFirst.textLabel?.text = "Language"
注意:如果您在 TableViewCell 上附加了标签,则只需使用情节提要将其隐藏即可。
【讨论】:
希望它有效:
@IBOutlet weak var yourTextField: UITextField!
private var yourText: String?
我只是在这个 tableview 的委托中自定义:
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
guard let yourText = yourText else { return }
yourTextField.text = yourText
}
当你改变文字时:
yourText = "New text here"
tableView.reloadData()
【讨论】:
你可以这样做
for (int section = 0; section < [table numberOfSections]; section++) {
for (int row = 0; row < [table numberOfRowsInSection:section]; row++) {
NSIndexPath* cellPath = [NSIndexPath indexPathForRow:row inSection:section];
UITableViewCell* cell = [self cellForRowAtIndexPath:cellPath];
cell.backgroundColor = [UIColor blackColor];
cell.textLabel.textColor = [UIColor whiteColor;
cell.textLabel.text = @"Your text";
}
}
另外,请确保将您的更改置于 viewDidAppear 之外,并将它们放在 viewWillAppear 中,否则您会遇到问题
【讨论】:
你可以试试
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath)
{
cell.textLabel?.text = titles[indexPath.row]
}
【讨论】: