[英]Adapting code to viewDidLoad instead of UITableView
我有以前在UITableView方法中调用的这段代码
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
但是,我现在想在viewDidLoad中使用此代码,但是此代码当然无法工作,因为它使用的是objectatIndex:.row-我需要在代码中进行哪些更改才能使它在viewDidLoad中工作
SKProduct * product = (SKProduct *) [_products objectAtIndex:.row];
_priceFormatter = [[NSNumberFormatter alloc] init];
[_priceFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[_priceFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[_priceFormatter setLocale:product.priceLocale];
labelPrice.text = [_priceFormatter stringFromNumber:product.price];
只需将indexPath.row
替换为所需对象的索引号即可。 例如,如果要第一个对象仅使用:
SKProduct * product = (SKProduct *) [_products objectAtIndex:0];
看来您已经为价格格式化程序声明了一个iVar。 如果是这种情况,请将此代码放入viewDidLoad中:
_priceFormatter = [[NSNumberFormatter alloc] init];
[_priceFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[_priceFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[_priceFormatter setLocale:product.priceLocale];
这是更有效的方法,因为我们可以为每个单元格使用相同的NSNumberFormatter,而不是一直创建新单元格。
然后,可以将以下代码放在cellForRowAtIndexPath中:
SKProduct * product = (SKProduct *) [_products objectAtIndex:indexPath.row];
labelPrice.text = [_priceFormatter stringFromNumber:product.price];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.