自定义大小的表格视图单元格中的 UILabel 中的行数
Posted
技术标签:
【中文标题】自定义大小的表格视图单元格中的 UILabel 中的行数【英文标题】:Number of lines in UILabel in self-sizing tableview cell 【发布时间】:2015-06-25 06:16:00 【问题描述】:EDIT 2-我能够通过使用在不同问题 (https://***.com/a/14413484/2584268) 中找到的不同方法来使其工作,但我还将它与 GeneratorOfOne 提供的代码相结合,并且我在下面发布了我的结果。不过,我仍然遇到这个最终目标的问题。目标是在每一行文本旁边都有行号,有点像在代码编辑器中。问题是我需要保持连续的行数,所以如果第一个单元格中有 3 行,第二个单元格中的行号应该从 4 开始,依此类推,但我不相信我能做到这一点因为单元格中正在计算行数,所以我无法将值返回到 tableview 以设置第二个标签的文本(行号)......有什么想法吗?
override func layoutSubviews()
super.layoutSubviews()
calculateNumberOfLines()
var textDetail: String?
didSet
gameInfo.text = textDetail
func calculateNumberOfLines()
let layoutManager = NSLayoutManager()
let textStorage = NSTextStorage(string: self.gameInfo!.text!)
textStorage.addAttribute(NSFontAttributeName, value: self.gameInfo!.font, range: NSMakeRange(0, textStorage.length))
let textContainer = NSTextContainer(size: CGSize(width:self.contentView.bounds.size.width - 56.0, height: CGFloat.max))
layoutManager.addTextContainer(textContainer)
layoutManager.textStorage = textStorage
if let text = gameInfo?.text
let numberOfLines = getLinesArrayOfStringInLabel(gameInfo)
lineNumbers.text = "\(startingNum)"
for index in startingNum+1...startingNum+numberOfLines
lineNumbers.text = lineNumbers.text?.stringByAppendingString("\n\(index)")
endingNum = startingNum+numberOfLines
//let numberOfLines = totalNumberOfLinesIn(text, currentGlyphIndex:0, currentLineNumber: 1, layoutManager: layoutManager, textContainer: textContainer)
//lineNumbers.text = "\(numberOfLines)"
else return
func getLinesArrayOfStringInLabel(label: UILabel) -> Int
var text = label.text as! NSString
var font = label.font
var rect = label.frame
var myFont = CTFontCreateWithName(font.fontName, font.pointSize, nil)
var attrString = NSMutableAttributedString(string: text as String)
attrString.addAttribute(String(kCTFontAttributeName), value: myFont, range: NSMakeRange(0, attrString.length))
let frameSetter = CTFramesetterCreateWithAttributedString(attrString)
var path = CGPathCreateMutable()
CGPathAddRect(path, nil, CGRectMake(0,0,rect.size.width,100000))
var frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, nil)
var lines = CTFrameGetLines(frame) as NSArray
var linesArray = NSMutableArray()
for line in lines as [AnyObject]
var lineRef = line as! CTLineRef
var lineRange = CTLineGetStringRange(lineRef)
var range = NSMakeRange(lineRange.location, lineRange.length)
var lineString = text.substringWithRange(range)
linesArray.addObject(lineString)
return linesArray.count
我有一个自定义 UITableViewCell 子类,它使用自调整大小的单元格。单元格的大小是完美的,并且标签正在正确扩展。但是,在运行时,我试图计算标签将扩展到的行数(我需要在标签旁边显示行号),但我无法实现这一点。我尝试了以下两种方法,但似乎都没有返回应用程序运行时看到的正确行数:
func lineCountForText(string: String, label: UILabel) -> Int
let font: UIFont = UIFont(name: "SourceCodePro-Regular", size: label.font.pointSize)!
let rect = string.boundingRectWithSize(CGSizeMake(label.frame.width, CGFloat(MAXFLOAT)), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [font : NSFontAttributeName], context: nil)
return Int(ceil(rect.size.height/font.lineHeight))
func numberOfLinesForString(string: String, size: CGSize, font: UIFont) -> Int
let textStorage = NSTextStorage(string: string, attributes: [NSFontAttributeName: font])
let textContainer = NSTextContainer(size: size)
textContainer.lineBreakMode = .ByWordWrapping
textContainer.maximumNumberOfLines = 0
textContainer.lineFragmentPadding = 0
let layoutManager = NSLayoutManager()
layoutManager.textStorage = textStorage
layoutManager.addTextContainer(textContainer)
var numberOfLines = 0
var index = 0
var lineRange : NSRange = NSMakeRange(0, 0)
for (; index < layoutManager.numberOfGlyphs; numberOfLines++)
layoutManager.lineFragmentRectForGlyphAtIndex(index, effectiveRange: &lineRange)
index = NSMaxRange(lineRange)
return numberOfLines
我无法做到这一点,因为它是一个自动调整大小的单元格吗?
编辑-这是我正在使用的文本数组:
var randomSizedTexts = [
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\nUt enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur?",
"Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem",
", sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora",
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident",
"Et harum quidem rerum facilis est et expedita distinctio",
"Mauris id efficitur sapien. Nunc lobortis nisi ut ultricies scelerisque. Curabitur accumsan sit amet lacus in finibus. Aliquam dolor ante, rhoncus sit amet fermentum et, semper sit amet nisi. Proin pretium velit ut quam mollis fringilla. Nullam neque risus, vestibulum eget tortor sit amet, suscipit ultricies metus. In tortor ipsum, feugiat lacinia leo id, pulvinar lacinia velit. Suspendisse sit amet porta tellus, et scelerisque odio. Nam convallis sodales congue. Proin vel quam id arcu nisi non.",
]
【问题讨论】:
当您调用lineCountForText
或numberOfLinesForString
方法时?
@Bannings 他们没有返回正确的行数
label
的宽度是否正确?
@Bannings 是的。
我还在等你的回复
【参考方案1】:
尝试使用NSAttributedString
:
func lineCountForLabel(label: UILabel) -> Int
let font: UIFont = label.font
let attribtedString = label.attributedText.mutableCopy() as! NSMutableAttributedString
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = label.lineBreakMode
attribtedString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSRange(location: 0, length: attribtedString.length))
let rect = attribtedString.boundingRectWithSize(CGSizeMake(label.frame.width, CGFloat(MAXFLOAT)),
options: .UsesLineFragmentOrigin | .UsesFontLeading,
context: nil)
return Int(ceil(rect.size.height/font.lineHeight))
更新:
你可以将字典的类型简写为[Key: Value],所以你的这行是不正确的:
let rect = string.boundingRectWithSize(xx, xx, xx, attributes: [font : NSFontAttributeName], context: nil)
改变:
[font : NSFontAttributeName]
到:
[NSFontAttributeName : font]
更新(问题更新后)
你应该像这样在你的数据源中存储一个行号:
class MyCell: UITableViewCell
@IBOutlet var contentLabel: UILabel!
@IBOutlet private var numberLabel: UILabel!
class MasterViewController: UITableViewController
var objects = [AnyObject]()
override func viewDidLoad()
super.viewDidLoad()
let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:")
self.navigationItem.rightBarButtonItem = addButton
self.tableView.estimatedRowHeight = 44
self.tableView.rowHeight = UITableViewAutomaticDimension
self.insertNewObject(self)
self.insertNewObject(self)
self.insertNewObject(self)
self.insertNewObject(self)
self.insertNewObject(self)
self.insertNewObject(self)
self.insertNewObject(self)
self.insertNewObject(self)
self.insertNewObject(self)
self.insertNewObject(self)
func insertNewObject(sender: AnyObject)
var count = Int(arc4random_uniform(20)) + 1
var string = ""
while (count-- > 0)
string += "This is a test."
objects.insert(["content" : string, "lineNumber" : 0], atIndex: 0)
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int
return 1
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
return objects.count
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! MyCell
var object = objects[indexPath.row] as! [String : AnyObject]
var startLineNumber = 0
if indexPath.row > 0
var pObject = objects[indexPath.row - 1] as! [String : AnyObject]
startLineNumber = pObject["lineNumber"] as! Int
cell.contentView.setNeedsLayout()
cell.contentView.layoutIfNeeded()
cell.contentLabel.text = object["content"] as? String
let lineNumber = lineCountForLabel(cell.contentLabel) + startLineNumber
cell.numberLabel.text = "\(lineNumber)"
object["lineNumber"] = lineNumber
objects[indexPath.row] = object
return cell
func lineCountForLabel(label: UILabel) -> Int
let font: UIFont = label.font
let attribtedString = label.attributedText.mutableCopy() as! NSMutableAttributedString
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = label.lineBreakMode
attribtedString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSRange(location: 0, length: attribtedString.length))
let rect = attribtedString.boundingRectWithSize(CGSizeMake(label.frame.width, CGFloat(MAXFLOAT)),
options: .UsesLineFragmentOrigin | .UsesFontLeading,
context: nil)
return Int(ceil(rect.size.height/font.lineHeight))
更新:
您的演示中有一些问题。
改变
lastNumUsed = 1
到
lastNumUsed = 0
改变
for index in lastNumUsed+1...lastNumUsed+numLines
到
for index in lastNumUsed+1...lastNumUsed+numLines-1
最后,问题的关键在于gameInfo
的大小是否正确。当cellForRow
执行它的超级视图时可能为零,因此单元格的大小和gameInfo
不正确。相反,您应该像这样计算willDisplayCell
中的行数:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
var cell: LineNumberSubtitleCell! = tableView.dequeueReusableCellWithIdentifier("GameCell", forIndexPath: indexPath) as! LineNumberSubtitleCell
if cell == nil
cell = LineNumberSubtitleCell(style: UITableViewCellStyle.Default, reuseIdentifier: "GameCell")
cell.gameInfo.text = randomSizedTexts[indexPath.row]
return cell
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath)
let cell = cell as! LineNumberSubtitleCell
cell.contentView.setNeedsLayout()
cell.contentView.layoutIfNeeded()
let numLines = getLinesArrayOfStringInLabel(cell.gameInfo)
cell.lineNumbers.text = "\(lastNumUsed)"
if !(lineNumbersList.count > indexPath.row)
for index in lastNumUsed+1...lastNumUsed+numLines-1
cell.lineNumbers.text = cell.lineNumbers.text?.stringByAppendingString("\n\(index)")
if index == lastNumUsed+numLines-1
lastNumUsed = index+1
lineNumbersList.addObject(cell.lineNumbers.text!)
else
cell.lineNumbers.text = lineNumbersList.objectAtIndex(indexPath.row) as? String
调用setNeedsLayout
方法会强制您的视图更新其布局。调用layoutIfNeeded
方法会强制布局系统现在运行。所以gameInfo
的大小应该重新计算才能更正。
【讨论】:
这似乎有效,在做了一些额外的日志记录之后,看起来我的方法也有效。问题是,这些方法被调用的次数是它们应该调用的两倍。第一次调用它们(每个单元格一次),它们返回正确的数字,然后由于某种原因,它们再次被调用并返回不正确的值,这是我在日志中看到的日志语句,不正确的行数字,但我需要弄清楚为什么它会被调用两次。我在滚动视图中使用我的表格视图在多个 VC 之间向左/向右滑动,我认为这可能是原因。 我在github.com/zhangao0086/DKTabPageViewController中实现了类似的东西 我使用的是github.com/malcommac/DMCircularScrollView,我稍微修改了一下 我认为这个问题与“viewsFromIndex”方法有关,因为这是我的日志语句在标签方法被调用两次之前的位置。 我认为您应该确保lineCountForText
始终返回正确的数字。也就是说,问题的关键在于字符串和标签是否正确。【参考方案2】:
您可以将 labelHeight/12.0f 用于行数,其中 12.0f 是正在使用的字体大小。
【讨论】:
【参考方案3】:这是一个计算文本行数的简单示例。
该方法递归地查找字形索引,并获取一个线段并比较索引处的字形是否是最后一个。
class TableViewCell: UITableViewCell
var index: Int = 0
var titleLabel: UILabel!
var numberOfLinesLabel: UILabel!
override init(style: UITableViewCellStyle, reuseIdentifier: String?)
super.init(style: style, reuseIdentifier: reuseIdentifier)
titleLabel = UILabel(frame: CGRectZero)
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.numberOfLines = 0
titleLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
contentView.addSubview(titleLabel)
numberOfLinesLabel = UILabel(frame: CGRectZero)
numberOfLinesLabel.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(numberOfLinesLabel)
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-10-[titleLabel]-10-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["titleLabel": titleLabel]))
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-20-[titleLabel]-[numberOfLinesLabel(==28)]|", options: NSLayoutFormatOptions.AlignAllTop, metrics: nil, views: ["titleLabel": titleLabel, "numberOfLinesLabel": numberOfLinesLabel]))
required init(coder aDecoder: NSCoder)
fatalError("init(coder:) has not been implemented")
var textDetail: String?
didSet
titleLabel.text = textDetail
override func layoutSubviews()
super.layoutSubviews()
calculateNumberOfLines()
func calculateNumberOfLines()
let layoutManager = NSLayoutManager()
let textStorage = NSTextStorage(string: self.titleLabel!.text!)
textStorage.addAttribute(NSFontAttributeName, value: self.titleLabel!.font, range: NSMakeRange(0, textStorage.length))
let textContainer = NSTextContainer(size: self.titleLabel!.bounds.size)
layoutManager.addTextContainer(textContainer)
layoutManager.textStorage = textStorage
guard let text = titleLabel?.text else return
let numberOfLines = totalNumberOfLinesIn(text: text, currentGlyphIndex:0, currentLineNumber: 1, layoutManager: layoutManager, textContainer: textContainer)
numberOfLinesLabel.text = "\(numberOfLines)"
func totalNumberOfLinesIn(text text: String, currentGlyphIndex glyphIndex:Int, currentLineNumber line:Int, layoutManager: NSLayoutManager, textContainer: NSTextContainer) -> Int
let maxGlyphIndex = layoutManager.glyphRangeForTextContainer(textContainer)
let lineFragment = layoutManager.lineFragmentRectForGlyphAtIndex(glyphIndex, effectiveRange: nil)
let glyphRange = layoutManager.glyphRangeForBoundingRect(lineFragment, inTextContainer: textContainer)
if NSMaxRange(glyphRange) < NSMaxRange(maxGlyphIndex)
return totalNumberOfLinesIn(text: text, currentGlyphIndex:glyphIndex + glyphRange.length, currentLineNumber: (line + 1), layoutManager: layoutManager, textContainer: textContainer)
return line
class TestViewController: UIViewController
static let CellIdentifier = "CellIdentifier"
var randomSizedTexts = [
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\nUt enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur?",
"Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem",
", sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora",
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident",
"Et harum quidem rerum facilis est et expedita distinctio",
"Mauris id efficitur sapien. Nunc lobortis nisi ut ultricies scelerisque. Curabitur accumsan sit amet lacus in finibus. Aliquam dolor ante, rhoncus sit amet fermentum et, semper sit amet nisi. Proin pretium velit ut quam mollis fringilla. Nullam neque risus, vestibulum eget tortor sit amet, suscipit ultricies metus. In tortor ipsum, feugiat lacinia leo id, pulvinar lacinia velit. Suspendisse sit amet porta tellus, et scelerisque odio. Nam convallis sodales congue. Proin vel quam id arcu nisi non.",
]
lazy var tableView: UITableView! =
let tableView = UITableView(frame: CGRectZero, style: .Plain)
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.delegate = self
tableView.dataSource = self
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44
self.view.addSubview(tableView)
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[tableView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["tableView": tableView]))
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[tableView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["tableView": tableView]))
return tableView
()
override func viewDidLoad()
super.viewDidLoad()
view.backgroundColor = UIColor.whiteColor()
tableView.registerClass(TableViewCell.self, forCellReuseIdentifier: TestViewController.CellIdentifier)
extension TestViewController: UITableViewDataSource, UITableViewDelegate
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
let cell = tableView.dequeueReusableCellWithIdentifier(TestViewController.CellIdentifier, forIndexPath: indexPath) as! TableViewCell
cell.index = indexPath.row
cell.textDetail = randomSizedTexts[indexPath.row]
return cell
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
return randomSizedTexts.count
更新:根据 titleLabel 大小设置 NSTextContainer 大小似乎不合适。由于此时 titleLabel 的大小不太合适。似乎手动计算可用于显示标签的边界的大小会给出正确的结果。请查看更改。
【讨论】:
感谢您非常详细的回答,非常感谢!我刚刚在我的项目中实现了您的想法,并且它在大多数情况下都有效,但是当我滚动表格时,某些行号会减一。它要么比实际行数多一,要么少一。这可能是什么原因造成的?最后是否有额外的空间被推到下一行或什么的?和我用的字体有关系吗? 我已尝试将您提供的文本缩小一些,并且能够重现不正确的行号,我将使用我使用的数组编辑我的问题... @Jacob 请看我的编辑。这应该可以解决您的问题:) 好的,你用的怎么样?你如何计算分配给 NSTextContainer 的边界。 我不记得到底是什么问题,但是将标签的边界大小提供给 NSTextContainer 可以解决问题。你能不能试试。【参考方案4】:为所有单元格实现动态高度。 这是一个例子。在此示例中,单元格有一个标签。
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
cellHeight = 40.0f; // Height excluding label height
// Calculate label height
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 288, 0)];
label.font = [UIFont systemFontOfSize:13];
label.text = [details objectAtIndex:indexPath.row];
label.numberOfLines = 0;
[label sizeToFit];
cellHeight += [PSIUtility heightForLabel:label];
label.text = [tips objectAtIndex:indexPath.row];
label.numberOfLines = 0;
[label sizeToFit];
cellHeight += [self heightForLabel:label];
//Return cell Height
return cellHeight;
- (CGFloat)heightForLabel:(UILabel *)label
//Calculate the expected size based on the font and linebreak mode of your label
// FLT_MAX here simply means no constraint in height
label.numberOfLines = 0;
CGSize maximumLabelSize = CGSizeMake(label.frame.size.width, FLT_MAX);
// CGSize expectedLabelSize = [label.text sizeWithFont:label.font constrainedToSize:maximumLabelSize lineBreakMode:label.lineBreakMode];
CGRect expectedLabelSize = [label.text boundingRectWithSize:maximumLabelSize
options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
attributes:@NSFontAttributeName:label.font
context:nil];
return expectedLabelSize.size.height;
【讨论】:
这并没有回答我的问题,它实际上是实现自调整单元格的错误方法。我正在使用 UITableviewAutomaticDimension 的动态单元格高度,我想找到标签将具有的行数,而不是高度。以上是关于自定义大小的表格视图单元格中的 UILabel 中的行数的主要内容,如果未能解决你的问题,请参考以下文章
如何使用自定义表格视图单元格中识别的点击手势从 UILabel 呈现视图控制器?