iPhoneアプリのUILabelの中央に単語を配置する必要があります。長すぎてラベルに収まらないテキストの文字列があるので、ラベルを特定の単語の中央に配置し、末尾を切り捨てたいと思います。例:これはサンプル文です。「こんにちは、私はUILabelの長い文から単語を中央に配置しようとして立ち往生しています。」UILabelが「...私は立ち往生している...」のように見えるように、「スタック」という単語を中心に置きたいと思います。同じ質問のリンクを見つけましたが、答えが得られませんでした。私はこの種のプログラミングに非常に慣れていないので、さらに助けていただければ幸いです。前もって感謝します。他の質問へのリンクは次のとおりです。iOS:UILabel内の文の中央に単語を配置するアルゴリズム
質問する
340 次
2 に答える
3
これをコーディングして実行しました(ただし、エッジケースはテストしませんでした)。アイデアは、中央に配置される単語の周りに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のカテゴリメソッドに変更できます。
于 2012-04-26T04:25:48.870 に答える
0
提案:2つのラベルを使用します。1つは左揃え、もう1つは右揃えです。両方とも、「外側」(表示)ラベルの境界線の外側で切り捨てられ、並べて配置する必要があります。あなたの中心的な単語が両方の間のトランジットを構成するというあなたの文を配布してください。
このようにすると、完全な中央揃えは得られませんが(中央の単語の長さによって異なります)、それに近くなります。
于 2012-04-26T03:56:15.807 に答える