首页 > 解决方案 > 在 Swift 中的 Tableviewcell 中格式化数据内容

问题描述

它应该是什么样子。

它应该是什么样子

它目前的样子。

它目前的样子

我正在尝试在我的 tableview 单元格上显示信息。上图中的第一个单元格信息看起来不错,但仅当表格视图处于编辑模式时 - 我只希望所有单元格在正常模式下都显示相同的内容。

这是我下面的代码 //cellForRow 方法

var cell = UITableViewCell(style: UITableViewCellStyle.value1, reuseIdentifier: celliD)

cell?.textLabel?.numberOfLines = 0
cell?.detailTextLabel?.numberOfLines = 0
cell?.accessoryView = nil
cell?.tintColor = UIColor.cmoOrangeColor
cell?.textLabel?.textColor = UIColor.darkGray
cell?.detailTextLabel?.textColor = UIColor.lightGray

let animalEntity = self.newSaleSelectedAnimalsManagedObject[indexPath.row] as? AnimalEntity
cell?.textLabel?.attributedText = AnimalFacade.animalTitleAttributedText(animalEntity: animalEntity!, withHolding: false)

cell?.detailTextLabel?.attributedText = AnimalFacade.animalDetails()

return cell!

//textLabel 格式化数据

class func animalTitleAttributedText(animalEntity: AnimalEntity, withHolding: Bool) -> NSMutableAttributedString  {

    //AttributedText
    let attributedTitle = NSDictionary(object: UIFont.tableViewCellTitle as Any, forKey: NSFontAttributeName as NSCopying) as? [String : Any]
    let attributedSubtitle = NSDictionary(object: UIFont.tableViewCellSubtitle as Any, forKey: NSFontAttributeName as NSCopying) as? [String : Any]

    //TextLabel
    let titleAttributedText = NSMutableAttributedString()


    //officialTag
    let officialTag = animalEntity.officialTag //UK 123456 123456
    let mgtTag = animalEntity.managementTag //WER3456
    let age = DateUtil.calculateAge(dateTime: animalEntity.dob! as Date) //13 y
    let animalCategory = animalEntity.animalTag //Heifer Calf
    let breed = animalEntity.breed //AB

    titleAttributedText.append(NSAttributedString(string: officialTag! + "\n", attributes: attributedTitle))
    titleAttributedText.append(NSAttributedString(string: "Mgmt Tag: \(mgtTag!), \(age), \(animalCategory!), \(breed!) \n", attributes: attributedSubtitle))

    return titleAttributedText
}

//detailLabel格式化数据

class func animalDetails() -> NSMutableAttributedString {

    let attributedSubtitle = NSDictionary(object: UIFont.tableViewCellSubtitle as Any, forKey: NSFontAttributeName as NSCopying) as? [String : Any]

    //detailsLabel
    let detailsAttributedText = NSMutableAttributedString()

    let price = "1234.85"
    let lotNumber = "TREPOU123"

    detailsAttributedText.append(NSAttributedString(string: price + "\n\n", attributes: attributedSubtitle))
    detailsAttributedText.append(NSAttributedString(string: lotNumber, attributes: attributedSubtitle))

    return detailsAttributedText
}

标签: iosswiftuitableview

解决方案


推荐阅读