我目前使用UILabel
来显示多行文本。大多数换行符设置为NSLineBreakByWordWrapping
,因此标签会自动插入换行符。我如何检测这些换行符在哪里?基本上,我想返回一个包含每个\n
中断的字符串。UILabel检测换行符
回答
这是我的工作,各地用于检测换行内UILabel
- (int)getLengthForString:(NSString *)str fromFrame:(CGRect)frame withFont:(UIFont *)font
{
int length = 1;
int lastSpace = 1;
NSString *cutText = [str substringToIndex:length];
CGSize textSize = [cutText sizeWithFont:font constrainedToSize:CGSizeMake(frame.size.width, frame.size.height + 500)];
while (textSize.height <= frame.size.height)
{
NSRange range = NSMakeRange (length, 1);
if ([[str substringWithRange:range] isEqualToString:@" "])
{
lastSpace = length;
}
length++;
cutText = [str substringToIndex:length];
textSize = [cutText sizeWithFont:font constrainedToSize:CGSizeMake(frame.size.width, frame.size.height + 500)];
}
return lastSpace;
}
-(NSString*) getLinebreaksWithString:(NSString*)labelText forWidth:(CGFloat)lblWidth forPoint:(CGPoint)point
{
//Create Label
UILabel *label = [[UILabel alloc] init];
label.text = labelText;
label.numberOfLines = 0;
label.lineBreakMode = NSLineBreakByWordWrapping;
//Set frame according to string
CGSize size = [label.text sizeWithFont:label.font
constrainedToSize:CGSizeMake(lblWidth, MAXFLOAT)
lineBreakMode:UILineBreakModeWordWrap];
[label setFrame:CGRectMake(point.x , point.y , size.width , size.height)];
//Add Label in current view
[self.view addSubview:label];
//Count the total number of lines for the Label which has NSLineBreakByWordWrapping line break mode
int numLines = (int)(label.frame.size.height/label.font.leading);
//Getting and dumping lines from text set on the Label
NSMutableArray *allLines = [[NSMutableArray alloc] init];
BOOL shouldLoop = YES;
while (shouldLoop)
{
//Getting length of the string from rect with font
int length = [self getLengthForString:labelText fromFrame:CGRectMake(point.x, point.y, size.width, size.height/numLines) withFont:label.font] + 1;
[allLines addObject:[labelText substringToIndex:length]];
labelText = [labelText substringFromIndex:length];
if(labelText.length<length)
shouldLoop = NO;
}
[allLines addObject:labelText];
//NSLog(@"\n\n%@\n",allLines);
return [allLines componentsJoinedByString:@"\n"];
}
如何使用
NSString *labelText = @"We are what our thoughts have made us; so take care about what you think. Words are secondary. Thoughts live; they travel far.";
NSString *stringWithLineBreakChar = [self getLinebreaksWithString:labelText forWidth:200 forPoint:CGPointMake(15, 15)];
NSLog(@"\n\n%@",stringWithLineBreakChar);
你只需要设置由需要getLinebreaksWithString参数,你会获取包含每个“\ n”中断的字符串。
输出
这工作。尽管在一些字符串中,我遇到了“if([[str substringtringWithRange:range] isEqualToString:@”“]) ”returned“由于未捕获的异常'NSRangeException',原因:' - [__ NSCFString substringWithRange:] :范围或索引超出范围'“ – morcutt 2013-03-06 21:32:32
你可以只发布那些导致错误的示例字符串?可能是我可以找出 – 2013-03-07 04:07:13
@Bhargai我昨天遇到它,用RSS源测试它,但还没有重现相同的错误。下次发生时,我会发布它。我感谢您的帮助! – morcutt 2013-03-07 19:51:05
这是我解决这个问题。
我遍历所提供的字符串中的所有空白字符,将子字符串(从开始到当前空白)设置为我的标签,并检查高度的差异。当高度改变时,我插入一个新的行字符(模拟一个换行符)。
func wordWrapFormattedStringFor(string: String) -> String {
// Save label state
let labelHidden = label.isHidden
let labelText = label.text
// Set text to current label and size it to fit the content
label.isHidden = true
label.text = string
label.sizeToFit()
label.layoutIfNeeded()
// Prepare array with indexes of all whitespace characters
let whitespaceIndexes: [String.Index] = {
let whitespacesSet = CharacterSet.whitespacesAndNewlines
var indexes: [String.Index] = []
string.unicodeScalars.enumerated().forEach { i, unicodeScalar in
if whitespacesSet.contains(unicodeScalar) {
let index = string.index(string.startIndex, offsetBy: i)
indexes.append(index)
}
}
// We want also the index after the last character so that when we make substrings later we include also the last word
// This index can only be used for substring to this index (not from or including, since it points to \0)
let index = string.index(string.startIndex, offsetBy: string.characters.count)
indexes.append(index)
return indexes
}()
var reformattedString = ""
let boundingSize = CGSize(width: label.bounds.width, height: CGFloat.greatestFiniteMagnitude)
let attributes = [NSFontAttributeName: font]
var runningHeight: CGFloat?
var previousIndex: String.Index?
whitespaceIndexes.forEach { index in
let string = string.substring(to: index)
let stringHeight = string.boundingRect(with: boundingSize, options: .usesLineFragmentOrigin, attributes: attributes, context: nil).height
var newString: String = {
if let previousIndex = previousIndex {
return string.substring(from: previousIndex)
} else {
return string
}
}()
if runningHeight == nil {
runningHeight = stringHeight
}
if runningHeight! < stringHeight {
// Check that we can create a new index with offset of 1 and that newString does not contain only a whitespace (for example if there are multiple consecutive whitespaces)
if newString.characters.count > 1 {
let splitIndex = newString.index(newString.startIndex, offsetBy: 1)
// Insert a new line between the whitespace and rest of the string
newString.insert("\n", at: splitIndex)
}
}
reformattedString += newString
runningHeight = stringHeight
previousIndex = index
}
// Restore label
label.text = labelText
label.isHidden = labelHidden
return reformattedString
}
Image - Comparison of output string with label text.
该解决方案在我的情况的工作非常出色,希望它帮助。
- 1. 检查UILabel中是否有换行符
- 2. 检测UILabel换行符。将项目动态放入UITableViewCell中
- 3. Inputdlg不检测换行符
- 4. iPhone的UILabel与URL检测
- 5. 检测textarea自然换行符
- 6. 在UITextView中检测换行符
- 7. PHP:URL检测(regexp)包含换行符
- 8. 换行符在UILabel中不起作用
- 9. 用换行检测TextBlock中的换行符的数量?
- 10. 如何检测和一个char []替换换行符?
- 11. Java的检测和替换\ n换行符
- 12. 检测UILabel中显示的字符总数
- 13. 检测UILabel是否隐藏了另一个UILabel UIView
- 14. JQuery的检测换行符的字符串
- 15. 检测UILabel上的触摸事件
- 16. 如何检测哪个UILabel被窃听?
- 17. 如何检测UILabel中的省略号?
- 18. 用换行符对文本区域maxlength进行特征检测
- 19. 如何在PHP中检测多个换行符\ n?
- 20. 如何使用iTextSharp从PDF中检测换行符
- 21. 在php中可靠地检测换行符
- 22. 在jinja中检测sqlite3中的换行符
- 23. 用户的输入检测换行符(web2py的)
- 24. 在UITextView内部清除换行符时检测 - Objective C
- 25. 使用javascript检测文本中的换行符
- 26. 如何检测机器人的EditText换行符
- 27. 检测JavaScript中的换行符的问题范围对象
- 28. UITextView中的自动换行检测
- 29. 如何检测空格换行
- 30. UILabel文本不会自动换行
+1好问题 – 2013-03-06 09:48:51