Swift Dynamically created UILabel shows up twice

时间:2015-07-29 00:46:41

标签: ios swift uilabel

I have written a custom graph UIView subclass, and I use it to graph some basic data, and insert some user-defined data. As a final step, I'd like to add a UILabel on top of the graph with the user-defined data-point called out.

I highlight the point, and then create and add the UILabel:

    namespace Project\Entity;

This looks like it should work, but the UILabel is added twice. What am I doing wrong?

1 个答案:

答案 0 :(得分:0)

此代码可能位于drawRect。您正在drawRect进行子视图添加,这是不正确的。 drawRect在视图出现时至少被调用两次,之后可能会多次被调用。

您应该重写一些早期生命周期方法,例如awakeFromNib()或构造函数。在那里,构建您的标签并将其添加为子视图。这样addSubView()就会发生一次。标签将是不可见的,没有内容,所以不要担心。

drawRect中,只需更新标签的所有必要属性,包括frame

如果您发现实际上需要大量的文本“标签”,每个图表的数量不同,那么您根本不需要UILabel作为子视图。考虑使用someString.drawAtPoint(...)

直接在屏幕上绘制文字