如何以编程方式将文本添加到UIView
-
13-09-2020 - |
题
我有一个 UIView
我想添加几段文字。我用过一个 UITextView
但我认为这是矫枉过正的,因为它不需要可编辑。我想过用一个 UILabel
或一个 UITextField
, ,但我不明白你怎么告诉监督人员在哪里放置 UILabel
或 UITextField
内在。我想要一个最低的足迹对象,它可以让我把我选择的字体/颜色/大小的文本放在我的 UIView
在我想要的地方。不要问太多,嗯?
解决方案
对你来说最简单的方法是:
UILabel *yourLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 300, 20)];
[yourLabel setTextColor:[UIColor blackColor]];
[yourLabel setBackgroundColor:[UIColor clearColor]];
[yourLabel setFont:[UIFont fontWithName: @"Trebuchet MS" size: 14.0f]];
[yourSuperView addSubview:yourLabel];
在代码中构建或填充视图可能需要您使用 CGRectMake
有很多。正如它的名字所说,它创建了一个矩形,您可以使用它来设置您的超级视图的相对位置(相对于您的超级视图的边界)和大小。 UIView-Subclass
(在这种情况下a UILabel
).
它的工作原理是这样的:
yourLabel.Frame = CGRectMake(x, y, width, height); //x,y,width,height are float values.
x
定义超级视图的左边框和要添加的子视图的开头之间的间距,同样适用于 y
但与你的超级视图的顶部边界之间的间距有关。然后宽度和高度我认为是不言自明的。
希望这能让你走上正轨。
其他提示
您可以使用"center"来告诉UILabel在视图中的位置,而不是找到一种方法来告诉视图将uilabel定位在哪里。
例如。
myLabel.center = CGPointMake(0.0, 0.0);
希望您能够使用UILabel,对我来说它是灵活的不可编辑文本的基本形式。
对于Swift:
let yourLabel = UILabel(frame: CGRectMake(100, 100, 100, 100))
yourLabel.textColor = UIColor.whiteColor()
yourLabel.backgroundColor = UIColor.blackColor()
yourLabel.text = "mylabel text"
yoursuperview.addSubview(yourLabel)
这个问题很老,但是对于没有使用UILabel或UITextField的纯UIView文本选项(正如所有其他答案所描述的那样,但问题是如何在没有它们的情况下做到这一点),子类UIView中的drawRect像这样:
- (void)drawRect:(CGRect)rect{
NSString *string = @"Hello World!";
[string drawAtPoint:CGPointMake(100, 100) withFont:[UIFont boldSystemFontOfSize:16.0]];
}
此例程在X-Y位置显示文本
-(void)placeText:(NSString *)theText:(int)theX:(int)theY {
UILabel *textLabel;
// Set font and calculate used space
UIFont *textFont = [UIFont fontWithName:@"Helvetica" size:14];
CGSize textStringSize = [theText sizeWithFont:textFont constrainedToSize:CGSizeMake(300,50) lineBreakMode:NSLineBreakByTruncatingTail];
// Position of the text
textLabel = [[UILabel alloc] initWithFrame:CGRectMake(theX+OFFSETIMAGEX-(textStringSize.width/2), theY+OFFSETIMAGEY-(textStringSize.height/2), textStringSize.width,textStringSize.height)];
// Set text attributes
textLabel.textColor = [UIColor blackColor];
textLabel.backgroundColor = [UIColor orangeColor];
textLabel.font = textFont;
textLabel.text = theText;
// Display text
[self.view addSubview:textLabel];
}
可能很晚了,但这是我用的:-
CGRect labelFrame = CGRectMake(120,300, 530, 100);
UILabel *myLabel = [[UILabel alloc] initWithFrame:labelFrame];
//If you need to change the color
[myLabel setTextColor:[UIColor whiteColor]];
//If you need to change the system font
[myLabel setFont:[UIFont fontWithName:NULL size:23]];
//If you need alignment
[myLabel setTextAlignment:NSTextAlignmentCenter];
// The label will use an unlimited number of lines
[myLabel setNumberOfLines:0];
//Add label view to current view
[self.view addSubview:myLabel];
NSString *someString = @"Sample String, Yarp!";
myLabel.text = someString;
将UILabel添加到您的视图中。然后复盖视图的layoutSubviews方法。