ios - 使用分页符编辑 NSString

标签 ios objective-c uitableview nsstring

我正在使用 UITableView 在我的 iOS 应用程序中显示一些数据。问题是,cell.textLabel.text 和 cell.detailTextLabel.text 是可变的。例如,电话号码单元格可以是“Phone1”,也可以是“美国或加拿大的免费电话”。在第二种情况下,我想将字符串编辑为“美国或加拿大的免费电话”。所以我需要某种方法来获取一个字符串,确定它是否需要被剪切,如果需要则剪切它。

这是我目前所拥有的:

NSString *stringToCut;  // This would be inputted
NSString *newString;    // This is the resultant string
int maxLength = 15;     // The maximum length.

if ([stringToCut length] > maxLength)
{
    //This is the problem: How do I find a space (" ") near the middle?
    int half = [stringToCut length]/2;
    int locationOfSpaceNearHalf = ???
    newString = [stringToCut subStringFromIndex:locationOfSpaceNearHalf];
    newString = [newString stringByAppendingFormat:@"\n"];
    newString = [newstring stringByAppendingString:[stringToCut subStringFromIndex:locationofSpaceNearHalf+1]];
}
else 
{
    newString = stringToCut;
}

return newString;

我唯一能想到的就是做一个循环来生成所有空间的位置,然后找到最接近中间的那个。

更新

这里有两张图片,第一张是如果我们不对文本进行任何格式化的话,它会是什么样子。第二个是如果有格式化的话会是什么样子。

bad good

或者有更好的方法来格式化文本吗?

最佳答案

你想要实现什么目标?默认的 UILabel 行为还不够好吗? 不确定它是否有帮助,但您可以通过在 NSString 上调用 sizeWithFont:constrainedToSize: 来获取完整字符串的大小,并使用它来查看是否字符串是否适合...

如果这不是您的意思,请解释一下:)

关于ios - 使用分页符编辑 NSString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18281477/

相关文章:

ios - objective-c projet : join room 中的 Socket iOS swift 客户端

objective-c - 获取委托(delegate)方法的返回值

objective-c - OS X 中的 NSDataWritingFileProtectionComplete

ios - swift /XCode 6.4 : add back button to navigation controller in navigation bar

ios - 使用 tableViewCells 进行 Segue

ios - 从 Modal/Popover 展开 Segue,导致对开始/结束外观转换的调用不平衡

ios - FBSDKShareLinkContent 应用处于实时状态时无法共享标题和描述 iOS

ios - 调试扩展时如何打印变量?

ios - 使用和不使用协议(protocol)将选择器发送到 id 有什么区别?

swift - 如何使用 UITableViewCell 中的按钮添加 TextView