ios7以上已经摒弃 sizeWithFont 这个方法,需要用到 boundingRectWithSize 来获取文字的高度
1
2
3
4
5
6
7
8
9
10
11
12
|
UIFont
*font = [
UIFont
fontWithName
:
@"Arial"
size
:
1
4
];
//跟label的字体大小一样
CGSize
size = CGSizeMake(
3
0
0
,
2
9
9
9
9
);
//跟label的宽设置一样
if
(is_IOS_
7
)
{
NSDictionary
* dic = [
NSDictionary
dictionaryWithObjectsAndKeys
:font,
NSFontAttributeName
,nil];
size =[text
boundingRectWithSize
:size
options
:
NSStringDrawingUsesLineFragmentOrigin
|
NSStringDrawingUsesFontLeading
attributes
:dic
context
:nil
]
.size
;
}
else
{
size = [text
sizeWithFont
:font
constrainedToSize
:size
lineBreakMode
:NSLineBreakByCharWrapping];
//ios7以上已经摒弃的这个方法
}
|
UILabel根据内容自动调整高度
sizeWithFont已经被Apple抛弃了,但还是可以用的
sizeWithFont已经被Apple抛弃了,但还是可以用的
1
2
|
CGSize
size = [news_str
sizeWithFont
:label
.font
constrainedToSize
:CGSizeMake(label
.frame
.size
.width
, MAXFLOAT)
lineBreakMode
:NSLineBreakByWordWrapping];
label
.frame
= CGRectMake(label
.frame
.origin
.x
, label
.frame
.origin
.y
, size
.width
, size
.height
);
|
iOS7出来以后,以前的UILabel根据内容获得高度和宽度不建议用了,虽然还可以用,但是总有有强迫症的,不希望有警告,这段代码是iOS7以后UILabel可以根据内容改变高度和宽度。
1
2
3
4
5
6
7
8
|
NSString
*str =
@"866.44"
;
UIFont
*font = [
UIFont
systemFontOfSize
:
1
3
];
CGSize
size = CGSizeMake(
3
2
0
,
2
0
0
0
);
CGRect
labelRect = [str
boundingRectWithSize
:size
options
:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
attributes
:[
NSDictionary
dictionaryWithObject
:font
forKey
:NSFontAttributeName]
context
:nil
];
UILabel
*label = [[
UILabel
alloc
]initWithFrame:CGRectMake(
0
,
0
, labelRect
.size
.width
, labelRect
.size
.height
)];
label
.text
= str;
label
.font
= [
UIFont
systemFontOfSize
:
1
3
];
[
self
.view
addSubview
:
label
];
|
- /*根据label内容来调整label的高度*/
- - (void)resizeLabelByContent:(UILabel *)label
- {
- CGSize maxSize = CGSizeMake(label.width, 999);
- label.numberOfLines = 0;
- NSString *contentStr = label.text;
- UIFont *contentFont = label.font;
- CGRect contentFrame;
- NSString *version = [[UIDevice currentDevice] systemVersion];
- if ([version floatValue] < 7.0) {
- CGSize contentStringSize = [contentStr sizeWithFont:contentFont constrainedToSize:maxSize lineBreakMode:label.lineBreakMode];
- contentFrame = CGRectMake(label.left, label.top, label.width, contentStringSize.height);
- } else {
- NSDictionary *contentDic = [NSDictionary dictionaryWithObjectsAndKeys:contentFont, NSFontAttributeName, nil];
- CGSize contentStrSize = [contentStr boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:contentDic context:nil].size;
- contentFrame = CGRectMake(label.left, label.top, label.width, contentStrSize.height);
- }
- label.frame = contentFrame;
- }