iOS:以编程方式设置 UILabel 的字体大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17575626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
iOS: set font size of UILabel Programmatically
提问by LoneWolfPR
I'm trying to set the font size of a UILabel. No matter what value I put though the text size doesn't seem to change. Here's the code I'm using.
我正在尝试设置 UILabel 的字体大小。无论我输入什么值,文本大小似乎都没有改变。这是我正在使用的代码。
[self setTitleLabel:[[UILabel alloc] initWithFrame:CGRectMake(320.0,0.0,428.0,50.0)]];
[[self contentView] addSubview:[self titleLabel]];
UIColor *titlebg = [UIColor clearColor];
[[self titleLabel] setBackgroundColor:titlebg];
[[self titleLabel] setTextColor:[UIColor blackColor]];
[[self titleLabel] setFont:[UIFont fontWithName:@"System" size:36]];
回答by JohnVanDijk
Try [UIFont systemFontOfSize:36]
or [UIFont fontWithName:@"HelveticaNeue" size:36]
i.e. [[self titleLabel] setFont:[UIFont systemFontOfSize:36]];
尝试[UIFont systemFontOfSize:36]
或[UIFont fontWithName:@"HelveticaNeue" size:36]
即[[self titleLabel] setFont:[UIFont systemFontOfSize:36]];
回答by fujianjin6471
Objective-C:
目标-C:
[label setFont: [label.font fontWithSize: sizeYouWant]];
Swift:
迅速:
label.font = label.font.fontWithSize(sizeYouWant)
just changes font size of a UILabel.
只是更改 UILabel 的字体大小。
回答by Pranit
Swift 3.0 / Swift 4.2 / Swift 5.0
斯威夫特 3.0 / 斯威夫特 4.2 / 斯威夫特 5.0
labelName.font = labelName.font.withSize(15)
回答by ytbryan
If you are looking for swift code:
如果您正在寻找快速代码:
var titleLabel = UILabel()
titleLabel.font = UIFont(name: "HelveticaNeue-UltraLight",
size: 20.0)
回答by Gaurav
This code is perfectly working for me.
这段代码非常适合我。
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(15,23, 350,22)];
[label setFont:[UIFont systemFontOfSize:11]];
回答by Imrul Kayes
In Swift 3.0, you could use this code below:
在 Swift 3.0 中,您可以使用以下代码:
let textLabel = UILabel(frame: CGRect(x:containerView.frame.width/2 - 35, y:
containerView.frame.height/2 + 10, width: 70, height: 20))
textLabel.text = "Add Text"
textLabel.font = UIFont(name: "Helvetica", size: 15.0) // set fontName and Size
textLabel.textAlignment = .center
containerView.addSubview(textLabel) // containerView is a UIView
回答by Chetan Kumar
Its BECAUSE there is no font family with name @"System"
hence size:36
will also not work ...
因为没有带名称的字体系列,@"System"
因此size:36
也不起作用......
Check the fonts available in xcode in attribute inspector and try
在属性检查器中检查 xcode 中可用的字体并尝试
回答by Chetan Kumar
For iOS 8
对于 iOS 8
static NSString *_myCustomFontName;
+ (NSString *)myCustomFontName:(NSString*)fontName
{
if ( !_myCustomFontName )
{
NSArray *arr = [UIFont fontNamesForFamilyName:fontName];
// I know I only have one font in this family
if ( [arr count] > 0 )
_myCustomFontName = arr[0];
}
return _myCustomFontName;
}