She*_*lam 137 objective-c uikit uilabel ios swift
我想在UILabel旁边显示一个图像,但是UILabel有可变的文本长度,所以我不知道在哪里放置图像.我怎么能做到这一点?
Aar*_*ers 189
CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font
constrainedToSize:maximumLabelSize
lineBreakMode:yourLabel.lineBreakMode];
Run Code Online (Sandbox Code Playgroud)
什么是 - [NSString sizeWithFont:forWidth:lineBreakMode:]有用吗?
这个问题可能有你的答案,对我有用.
2014年,我在这个新版本中进行了编辑,基于Norbert的超便利评论!这做了一切.干杯
// yourLabel is your UILabel.
float widthIs =
[self.yourLabel.text
boundingRectWithSize:self.yourLabel.frame.size
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{ NSFontAttributeName:self.yourLabel.font }
context:nil]
.size.width;
NSLog(@"the width of yourLabel is %f", widthIs);
Run Code Online (Sandbox Code Playgroud)
Jak*_*lář 148
yourLabel.intrinsicContentSize.widthfor Objective-C/Swift
小智 49
在迅速
yourLabel.intrinsicContentSize().width
Run Code Online (Sandbox Code Playgroud)
Che*_*noy 33
iOS 6及更低版本的所选答案正确无误.
在iOS 7中,sizeWithFont:constrainedToSize:lineBreakMode:已被弃用.现在建议您使用boundingRectWithSize:options:attributes:context:.
CGRect expectedLabelSize = [yourString boundingRectWithSize:sizeOfRect
options:<NSStringDrawingOptions>
attributes:@{
NSFontAttributeName: yourString.font
AnyOtherAttributes: valuesForAttributes
}
context:(NSStringDrawingContext *)];
Run Code Online (Sandbox Code Playgroud)
请注意,返回值CGRect不是a CGSize.希望这对在iOS 7中使用它的人有所帮助.
jar*_*ora 12
在iOS8中,sizeWithFont已被弃用,请参阅
CGSize yourLabelSize = [yourLabel.text sizeWithAttributes:@{NSFontAttributeName : [UIFont fontWithName:yourLabel.font size:yourLabel.fontSize]}];
Run Code Online (Sandbox Code Playgroud)
您可以在sizeWithAttributes中添加所需的所有属性.您可以设置的其他属性:
- NSForegroundColorAttributeName
- NSParagraphStyleAttributeName
- NSBackgroundColorAttributeName
- NSShadowAttributeName
Run Code Online (Sandbox Code Playgroud)
等等.但可能你不需要其他人
小智 8
CGRect rect = label.frame;
rect.size = [label.text sizeWithAttributes:@{NSFontAttributeName : [UIFont fontWithName:label.font.fontName size:label.font.pointSize]}];
label.frame = rect;
Run Code Online (Sandbox Code Playgroud)
Swift 4 Answer谁在使用约束
label.text = "Hello World"
var rect: CGRect = label.frame //get frame of label
rect.size = (label.text?.size(attributes: [NSFontAttributeName: UIFont(name: label.font.fontName , size: label.font.pointSize)!]))! //Calculate as per label font
labelWidth.constant = rect.width // set width to Constraint outlet
Run Code Online (Sandbox Code Playgroud)
Swift 5 Answer正在使用约束
label.text = "Hello World"
var rect: CGRect = label.frame //get frame of label
rect.size = (label.text?.size(withAttributes: [NSAttributedString.Key.font: UIFont(name: label.font.fontName , size: label.font.pointSize)!]))! //Calculate as per label font
labelWidth.constant = rect.width // set width to Constraint outlet
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
115574 次 |
| 最近记录: |