如何将相同的子视图添加到不同的视图中?
抱歉,初学者的问题:
我已经创建了一个 UILabel 的实例,并且想将此 UILabel 的副本添加到 4 个不同的视图中。我尝试了以下代码,但它不起作用,因为我将 UILabel 分配给一个视图,然后将其分配给下一个视图 - 这会导致 UILabel 从第一个视图中删除。这样继续下去,所以我最终只将 UILabel 分配给最后一个视图:
UILabel *titleTitle = [[[UILabel alloc] initWithFrame:CGRectMake(120, -48, 100, 28)] autorelease];
titleTitle.text = @"Index";
titleTitle.textColor = [UIColor blackColor];
titleTitle.backgroundColor = [UIColor clearColor];
titleTitle.font = [UIFont fontWithName:@"Ballpark" size:25.0f];
[indexView addSubview:titleTitle];
[indexView2 addSubview:titleTitle];
[indexView3 addSubview:titleTitle];
[indexView4 addSubview:titleTitle];
如何设法将 UILabel 的副本分配给我的视图?
Sorry, a beginner's questions:
I have created an instance of an UILabel and would like to add copies of this UILabel to 4 different views. I tried the following code, but it won't work as I am assigning the UILabel to one view and then assign it to the next -- which results in the UILabel being removed from the first view. This carries on, so I end up with the UILabel being assigned only to the very last view:
UILabel *titleTitle = [[[UILabel alloc] initWithFrame:CGRectMake(120, -48, 100, 28)] autorelease];
titleTitle.text = @"Index";
titleTitle.textColor = [UIColor blackColor];
titleTitle.backgroundColor = [UIColor clearColor];
titleTitle.font = [UIFont fontWithName:@"Ballpark" size:25.0f];
[indexView addSubview:titleTitle];
[indexView2 addSubview:titleTitle];
[indexView3 addSubview:titleTitle];
[indexView4 addSubview:titleTitle];
How can I manage to assign copies of UILabel to my views?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你不能这样做。一个视图只能有一个父视图。如果您想定义一次标签并在多个地方使用类似定义的标签,则应该复制它。
编辑:@Michael Petrov 指出 UIView 及其子类不符合 NSCopying 协议。我很遗憾忽视了这一点。
如果他提供的答案对您来说太复杂,您可以创建一个辅助函数来为您生成一个新的 UILabel 实例。
从你的代码来看:
..等等。
You can't do this. A view can only have one parent. If you want to define a label once and use a similarly defined label in multiple places, you should copy it.
EDIT: @Michael Petrov pointed out that UIView and its subclasses do not conform to the NSCopying protocol. My bad for overlooking this.
If the answer that he provided is too complicated for you, you can create a helper function that will generate a new instance of UILabel for you.
And from your code:
.. and so on.
这对于您的需求来说可能有点过分了,但是如果您必须复制一个复杂的对象,那么归档和取消归档它应该可以工作:
This is probably overkill for your needs, but if you must copy a complex object, then archiving and unarchiving it should work:
这是不可能的,一个视图只能有一个父视图。
您需要将其从当前父级中删除才能将其添加到其他位置。
That's impossible, a view can only have one parent.
You will need to remove it from the current parent to add it elsewhere.
一个视图只能显示在一个父视图中。因此,您需要为每个父视图创建单独的标签。您可以通过编写辅助函数来减少输入。
A view can only be displayed in one parent view. So you'll need to create separate labels for each parent view. You can cut down on typing by writing a helper function.