我试图获取包含多个段落的文本的 tableView 单元格。属性字符串似乎是一种在段落之间获得额外空间的方法(比在字符串中进行两次换行更好看一些)。当我发现当您想在单元格中放置不同的文本时,IB 设置不适用于运行时。
我想出的主要事情是向 String 添加一个扩展(使用 Swift)
创建具有某些特征的属性字符串。这里的示例使用 Marker Felt 字体,因为它很容易与 Helvetica 区分开来。该示例还显示了段落之间的一些额外间距,以使它们彼此更加不同。
extension String {
func toMarkerFelt() -> NSAttributedString {
var style = NSMutableParagraphStyle()
style.paragraphSpacing = 5.0
let markerFontAttributes : [NSObject : AnyObject]? = [
NSFontAttributeName : UIFont(name: "Marker Felt", size: 14.0)!,
NSParagraphStyleAttributeName: style,
NSForegroundColorAttributeName : UIColor.blackColor()
]
let s = NSAttributedString(string: self, attributes: markerFontAttributes)
return s
}
}
然后,在我的自定义 tableViewCell 中,您将所需的文本发送给它,然后它将其转换为 UILabel 上的属性字符串。
// MarkerFeltCell.swift
class MarkerFeltCell: UITableViewCell {
@IBOutlet weak var myLabel: UILabel!
func configureCellWithString(inputString : String) {
myLabel.attributedText = inputString.toMarkerFelt()
}}
在带有 tableView 的视图控制器中,您应该在 viewDidLoad() 中注册您的单元格——我使用了一个 nib,所以类似于:
let cellName = "MarkerFeltCell"
tableView.registerNib(UINib(nibName: cellName, bundle: nil), forCellReuseIdentifier: cellName)
要让单元格弄清楚它应该有多高,请制作一个原型单元格,用于获取大小信息,并且永远不会添加到 tableView 中。所以,在你的
查看控制器的变量:
var prototypeSummaryCell : MarkerFeltCell? = nil
然后在(可能覆盖 - 取决于您的视图控制器)heightForRowAtIndexPath:
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
// ...
if xib == "MarkerFeltCell" {
if prototypeCell == nil {
prototypeCell = tableView.dequeueReusableCellWithIdentifier(xib) as? MarkerFeltCell
}
let width : CGFloat = tableView.bounds.width
let height : CGFloat = prototypeCell!.bounds.height
prototypeCell?.bounds = CGRect(x: 0, y: 0, width: width, height: height)
configureCell(prototypeCell!, atIndexPath: indexPath)
prototypeSummaryCell?.layoutIfNeeded()
let size = prototypeSummaryCell!.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
let nextHeight : CGFloat = ceil(size.height + 1.0)
return nextHeight
} else { // ...
在上面的代码中,prototypeCell会在第一次需要的时候填充。在完成自动调整大小过程后,prototypeCell 然后用于计算单元格的高度。您需要使用 ceil() 函数对高度进行四舍五入。我还添加了一些额外的软糖因素。
最后的代码位是您如何配置单元格的文本。对于此示例,只需:
func configureCell(cell :UITableViewCell, atIndexPath indexPath: NSIndexPath) {
if let realCell = cell as? MarkerFeltCell {
realCell.configureCellWithString("Multi-line string.\nLine 2.\nLine 3.") // Use \n to separate lines
}
}
另外,这是笔尖的照片。将标签固定到单元格的边缘(需要边距),但使用“大于或等于”约束,底部约束的优先级低于“必需”。
将标签的字体设置为 Attributed。实际的 IB 字体无关紧要。
这种情况下的结果: