【发布时间】:2016-12-14 07:29:50
【问题描述】:
我有一个 UITableView,其中每一行显示一个日期和时间以及一条消息(下面的屏幕截图)。我正在使用单个属性字符串来显示行中的文本(这是色差所必需的)。
因为我不想对月、日或小时进行零填充,所以冒号左侧的日期是可变长度的,这会导致消息列表看起来杂乱无章。
我想要的结果是让所有冒号垂直排列,以便消息排列,尽管日期中的字符数是可变的。实现这一目标的最佳方法是什么?
我基本上尝试了空格填充(通过检测月、日和小时的长度),但结果仍然不能完美对齐,并且可能会导致长(难看)的空白块需要填充三个(月、日期和小时)。也许有一种方法可以在所有角色之间平均分配这个额外的空间?
日期格式:
//choose format for the date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "M/d h:mma: "
dateFormatter.amSymbol = "am"
dateFormatter.pmSymbol = "pm"
进入视图:
//first put in the date
let classHistoryCellText = NSMutableAttributedString.init(string: formattedDate)
classHistoryCellText.addAttribute(NSForegroundColorAttributeName, value: UIColor.init(hex: "#00000", alpha: 0.3), range: NSMakeRange(0, lengthOfDate))
//append what the message is
classHistoryCellText.append(NSMutableAttributedString.init(string: classBeingViewed.classHistory[indexPath.row]["event"] as! String))
classHistoryCellText.addAttribute(NSForegroundColorAttributeName, value: UIColor.init(hex: "#00000"), range: NSMakeRange(lengthOfDate, classHistoryCellText.length - lengthOfDate))
//bold the entire thing and make it size fontSize
classHistoryCellText.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: fontSize), range: NSMakeRange(0, classHistoryCellText.length))
classHistoryCellToDisplay.textLabel?.attributedText = classHistoryCellText
结果:
【问题讨论】:
-
取2个标签,会更容易。
-
我强烈建议您使用 YYYY-MM-DD 作为日期(是的,用零填充)。这是 ISO 标准,如果您的应用有任何国际用户,他们会很感激的。您可能需要考虑其他两个选项...如果您填零,固定长度的字体将排列所有内容。其次,将日期和时间放在自己的一行上。在下面的下面一行添加注释。
标签: ios swift date formatting nsattributedstring