gpt4 book ai didi

iphone - 将 UILabel 中的单词居中的算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:35:28 24 4
gpt4 key购买 nike

我需要在 iPhone 应用程序的 UILabel 中居中放置一个单词。我有一串文本太长,无法放入标签中,因此我想让标签以特定单词为中心并截断两端。例如:这是一个例句。 “大家好,我一直在尝试将 UILabel 中长句子中的单词居中。”我想把重点放在“卡住”这个词上,以便 UILabel 看起来像这样,“......我卡住试图......”。我找到了指向具有相同问题的问题的链接,但我无法找到适合我的答案。我对这种编程很陌生,因此将不胜感激任何进一步的帮助!提前致谢。这是另一个问题的链接:iOS: Algorithm to center a word in a sentence inside of a UILabel

最佳答案

我只是编码并运行了这个(但没有测试任何边缘情况)。这个想法是围绕要居中的单词创建一个 NSRange,然后在每个方向上对称地增加该范围,同时测试截断字符串的像素宽度与标签的宽度。

- (void)centerTextInLabel:(UILabel *)label aroundWord:(NSString *)word inString:(NSString *)string {

// do nothing if the word isn't in the string
//
NSRange truncatedRange = [string rangeOfString:word];
if (truncatedRange.location == NSNotFound) {
return;
}

NSString *truncatedString = [string substringWithRange:truncatedRange];

// grow the size of the truncated range symmetrically around the word
// stop when the truncated string length (plus ellipses ... on either end) is wider than the label
// or stop when we run off either edge of the string
//
CGSize size = [truncatedString sizeWithFont:label.font];
CGSize ellipsesSize = [@"......" sizeWithFont:label.font]; // three dots on each side
CGFloat maxWidth = label.bounds.size.width - ellipsesSize.width;

while (truncatedRange.location != 0 &&
truncatedRange.location + truncatedRange.length + 1 < string.length &&
size.width < maxWidth) {

truncatedRange.location -= 1;
truncatedRange.length += 2; // move the length by 2 because we backed up the loc
truncatedString = [string substringWithRange:truncatedRange];
size = [truncatedString sizeWithFont:label.font];
}

NSString *ellipticalString = [NSString stringWithFormat:@"...%@...", truncatedString];
label.textAlignment = UITextAlignmentCenter; // this can go someplace else
label.text = ellipticalString;
}

然后这样调用它:

[self centerTextInLabel:self.label aroundWord:@"good" inString:@"Now is the time for all good men to come to the aid of their country"];

如果你认为它是一个守护者,你可以把它改成一个 UILabel 上的类别方法。

关于iphone - 将 UILabel 中的单词居中的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10326948/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com