NSString
読み込まれているテキストに応じてを自動的にサイズ変更する追加機能がありますUILabel
(引用を表示する単純なアプリがあるため、いくつかの単語、いくつかの文です)。quote
そのラベルの下にはauthor
、(奇妙なことに) 引用の著者が含まれるラベルもあります。
author
そのラベルをラベルのすぐ下に配置しようとしていますquote
(そのy
座標は、quote
ラベルのy
座標にquote
ラベルのheight
. 、サイズが変わります。引用符が小さいほどスペースが多く、引用符が長いほどスペースが少なくなります。
layer.borderColor/borderWidth
赤と青のボックス (アプリで表示できるように設定したもの) の間のギャップは、見積もりが短いほど大きくなります。
誰かが以下のコードをふるいにかけて、不一致の原因を正確に指摘するのを手伝ってくれるなら、本当に感謝しています. 私が見る限り、author
ラベルは常にquote
ラベルのy + height
値の 35 ピクセル下にある必要があります。
確認のために: すべてが Interface Builder などで正しく接続されています。引用の内容はそこにうまく入っており、他のすべてが機能しているため、接続されています。それは問題ではありません。
明確にするために、私の質問は次のとおりです。引用符の長さに応じてラベル間のギャップが変化するのはなぜですか?35ピクセルの安定した設定可能なギャップを正しく取得するにはどうすればよいですか?
ラベルを配置するために使用しているコードは次のとおりです。
// Fill and format Quote Details
_quoteLabel.text = [NSString stringWithFormat:@"\"%@\"", _selectedQuote.quote];
_authorLabel.text = _selectedQuote.author;
[_quoteLabel setFont: [UIFont fontWithName: kScriptFont size: 28.0f]];
[_authorLabel setFont: [UIFont fontWithName: kScriptFontAuthor size: 30.0f]];
// Automatically resize the label, then center it again.
[_quoteLabel sizeToFitMultipleLines];
[_quoteLabel setFrame: CGRectMake(11, 11, 298, _quoteLabel.frame.size.height)];
// Position the author label below the quote label, however high it is.
[_authorLabel setFrame: CGRectMake(11, 11 + _quoteLabel.frame.size.height + 35, _authorLabel.frame.size.width, _authorLabel.frame.size.height)];
のカスタムメソッドは次のsizeToFitMultipleLines
とおりです。
- (void) sizeToFitMultipleLines
{
if (self.adjustsFontSizeToFitWidth) {
CGFloat adjustedFontSize = [self.text fontSizeWithFont: self.font constrainedToSize: self.frame.size minimumFontSize: self.minimumScaleFactor];
self.font = [self.font fontWithSize: adjustedFontSize];
}
[self sizeToFit];
}
そして、ここに私のfontSizeWithFont:constrainedToSize:minimumFontSize:
方法があります:
- (CGFloat) fontSizeWithFont: (UIFont *) font constrainedToSize: (CGSize) size minimumFontSize: (CGFloat) minimumFontSize
{
CGFloat fontSize = [font pointSize];
CGFloat height = [self sizeWithFont: font constrainedToSize: CGSizeMake(size.width, FLT_MAX) lineBreakMode: NSLineBreakByWordWrapping].height;
UIFont *newFont = font;
// Reduce font size while too large, break if no height (empty string)
while (height > size.height && height != 0 && fontSize > minimumFontSize) {
fontSize--;
newFont = [UIFont fontWithName: font.fontName size: fontSize];
height = [self sizeWithFont: newFont constrainedToSize: CGSizeMake(size.width, FLT_MAX) lineBreakMode: NSLineBreakByWordWrapping].height;
};
// Loop through words in string and resize to fit
for (NSString *word in [self componentsSeparatedByCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]]) {
CGFloat width = [word sizeWithFont: newFont].width;
while (width > size.width && width != 0 && fontSize > minimumFontSize) {
fontSize--;
newFont = [UIFont fontWithName: font.fontName size: fontSize];
width = [word sizeWithFont: newFont].width;
}
}
return fontSize;
}