objective-c - 在两个 UILabel 之间分割文本字符串以环绕图像

标签 objective-c ios nsarray uilabel word-wrap

我正在尝试在两个 UILabels 之间分离很长的文本,以便环绕图像。我重新使用并改编了该项目的前开发人员留下的一些代码,如下...

字符串(连续数字字,1 到 20):

NSString *sampleString = @"One two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty. One two three four five six seven eight nine ten. Eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty.";

分割方法...

-(void)seperateTextIntoLabels:(NSString*) text
{
    // Create array of words from our string
    NSArray *words = [text componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@" "]];

    //Data storage for loop
    NSMutableString *text1 = [[NSMutableString alloc] init];
    NSMutableString *text2 = [[NSMutableString alloc] init];

    for(NSString *word in words)
    {
        CGSize ss1 = [[NSString stringWithFormat:@"%@ %@",text1,word] sizeWithFont:descriptionLabel.font constrainedToSize:CGSizeMake(descriptionLabel.frame.size.width, 9999) lineBreakMode:descriptionLabel.lineBreakMode];

        if(ss1.height > descriptionLabel.frame.size.height || ss1.width > descriptionLabel.frame.size.width)
        {
            if( [text2 length]>0)
            {
                [text2 appendString: @" "];
            }
            [text2 appendString: word];
        }
        else {
            if( [text1 length]>0)
            {
                [text1 appendString: @" "];
            }
            [text1 appendString:word];
        }

    }
    descriptionLabel.text = text1;
    descriptionLabelTwo.text = text2;

    [descriptionLabel sizeToFit];
    [descriptionLabelTwo sizeToFit];

}

它的工作原理或多或少正如我所期望的那样,只是它在切换发生时变得困惑。

enter image description here

请注意标签 1“One”中的最后一个单词放错了位置。第二个标签的中间也缺少这个词。除了这个问题之外,其他方面似乎都可以正常工作。

对这里发生的事情有什么想法吗?

是否有其他解决方案?请注意,我不想使用 UIWebView(主要是因为屏幕渲染的延迟)。

最佳答案

好吧,这就是你的问题。

您正在检查字符串中的每个单词是否适合第一个标签,然后检查是否不适合。它进入第二个。直到“十二”,它都适合第一个标签。但是您希望其余字符串落入第二个标签,对吗?

在检查中,即使在分割到第二个标签之后,您仍会继续检查每个单词是否也适合第一个标签。 “One”是仍然适合第一个标签的第一个单词,因此将其放置在那里,并继续将其他单词放置在第二个标签中。

要解决这个“奇怪”的拆分问题,您可以为自己创建一个 bool 值,当您拆分到第二个标签时,该 bool 值将变为“YES”(或您喜欢的 true),并确保检查该 bool 值是否为打开并检查尺寸。

我希望这一切现在对您来说有意义。

祝你好运。

关于objective-c - 在两个 UILabel 之间分割文本字符串以环绕图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12069868/

相关文章:

ios - UITableViewCell 中的 UIButton 不会在点击时突出显示

ios - AVAssetWriter 忽略变换值

ios - 如何在 Swift 中使用 ios-chart API 选择 chartValueSelected 时为 lineChart 启用弹出窗口?

ios - 在 UIImagePickerController 中选择图像后的 MBProgressHUD

ios - 如何从 NSArray 输出中删除新行

ios - 重新定位 uilabel

ios - 检查对象是否在另一个对象的 RLMArray 属性中

ios - 使用 Xcode 签名的 MonoTouch 应用程序 iOS

ios - NSDictionary 未获取第一项 JSON

ios - 过滤巨大的 NSArray