如何在IOS中只用代码创建UILabel?

时间:2014-09-03 00:32:03

标签: ios uilabel

我知道如何自定义主故事板上已有的UILabel,但是有没有办法只用代码来定义和定位UILabel?

2 个答案:

答案 0 :(得分:0)

是的,有。

CGFloat x,y, width, height;
UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
myLabel.text = @"foo";
//Now add it to your view hierarchy
[self.view addSubview:myLabel];

我希望这会有所帮助。 我强烈建议您完成此View Programming Guide

答案 1 :(得分:0)

您可以在此处自定义故事板UILabel

// Create IBOutlet to get UILabel object in your view controller .m file
@property (weak, nonatomic) IBOutlet UILabel        *storyboardLabel;

// Go to storyboard and link this label to your storyboard label of this view controller

然后在代码下方放置您要重新定位或调整UILabel的大小。

// Get rect (position & size) of storyboard label
CGRect rect = self.storyboardLabel.frame;
rect.origin.x = 100; // Your preferable left position
rect.origin.y = 100; // Your preferable top position
rect.size.width = 200; // Your preferable label width
rect.size.height = 20; // Your preferable label height
[self.storyboardLabel setFrame:rect];