如何以编程方式将文本添加到 UIView
我有一个 UIView
,我想向其中添加几位文本。我使用了 UITextView
但我认为这太过分了,因为它不需要可编辑。我考虑过使用 UILabel
或 UITextField
,但我不知道如何告诉超级视图将 UILabel
或 放置在何处>UITextField
本身。我想要占用空间最小的对象,它可以让我将我选择的字体/颜色/大小的文本放置在我的 UIView
中我想要的位置。没什么好问的,是吗?
I have a UIView
that I'd like to add several bits of text to. I have used a UITextView
but I think that's overkill as it doesn't need to be editable. I thought about using a UILabel
or a UITextField
, but I don't see how you tell the superview where to position the UILabel
or UITextField
within itself. I want the lowest footprint object that will let me put text of a font/color/size of my choosing in my UIView
where I want it. Not too much to ask, eh?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
对您来说最简单的方法是:
在代码中构建或填充视图可能需要您大量使用
CGRectMake
。顾名思义,它创建一个矩形,您可以使用它来设置
UIView-Subclass
的相对位置(相对于超级视图的边框)和大小(在本例中为UILabel )。
它的工作原理如下:
x
定义超级视图的左边框与要添加的子视图的开头之间的间距,同样适用于y
但与超级视图的上边框之间的间距。那么我认为宽度和高度是不言自明的。
希望这能让你走上正轨。
The simplest approach for you would be:
Building or populating Views in your code will probably require you to use
CGRectMake
a lot.As its name says, it creates a rectangle that you can use to set the relative position (relative to the borders of your superview) and size of your
UIView-Subclass
(in this case aUILabel
).It works like this:
x
defines the spacing between the left hand border of the superview and the beginning of the subview your about to add, same applies toy
but relating to the spacing between top-border of your superview.then width and height are self-explanatory i think.
Hope this gets you on the track.
您可以使用“center”来告诉 UILabel 在视图中的位置,而不是找到一种方法来告诉视图将 UILabel 放置在何处。
例如,
希望您能够使用 UILabel,对我来说,它是灵活的不可编辑文本的基本形式。
Instead of finding a way to tell the view where to position the UILabel, you can tell the UILabel where to position itself in the view by using "center".
E.g.
Hope you'll be able to use UILabel, for me it's the basic form of a flexible non editable text.
对于斯威夫特:
For Swift:
这个问题很老了,但是对于不使用 UILabel 或 UITextField 的纯 UIView 文本选项(正如所有其他答案所描述的那样,但问题是如何在没有它们的情况下做到这一点),子类 UIView 中的 drawRect 对我有用。就像这样:
This question is old, but for a pure UIView text option without using UILabel or UITextField (as all the other answers describe, but the question is how to do it without them), drawRect in a subclassed UIView works for me. Like so:
此例程在 XY 位置显示文本
This routine displays a text at a X-Y position
可能会晚,但这是我使用的:-
It might be late but here is what I use:-
将 UILabel 添加到您的视图中。然后重写View的layoutSubviews方法。
add a UILabel to your View. then override the View's layoutSubviews method.