复制并重用放置在 IB 中的自定义 UIViewObject

Duplicate and Reuse a Custom UIViewObject placed in IB

我使用界面生成器创建了一个自定义 UIView 对象。此视图包含一个 UILabel 和一个 UIImageView。

我使用 interface builder 将此对象放置在 ViewController 中,并将 UIView 的 class 设置为 UIViewLabelImage。我在 class.h 文件中引用了 UILabel 和 UIImageView。 我还创建了一个 CustomOutlet 来操作这个新的 UIViewLabelImage 对象。

我设法使用 :

检索对象 UIViewLabelImage
  UIViewLabelImage *view = (UIViewLabelImage *)[self.view viewWithTag:101]; 
  //or using self.CustomOutlet.

我可以更改视图、文本和图像一切正常。

  self.CustomOutlet.img.backgroundColor = [UIColor redColor];

如果我想以编程方式添加另一个 UIViewLabelImage,它也可以。例如,我使用新标签检索新创建的对象。

但是当我尝试复制 UIViewLabelImage 时遇到问题。复制工作和屏幕上显示的对象与第一个相同,但我无法更改该标签的文本或图像。 这是因为 copyOFLabel.text 和 copyOFLabel.img 为零。

  UIViewLabelImage *copyOFLabel = [NSKeyedUnarchiver unarchiveObjectWithData:
  [NSKeyedArchiver archivedDataWithRootObject:self.CustomOutlet]];
  copyOFLabel.tag = 11;
  //copyOfLabel.text == nil 
  copyOFLabel.text.text = @"Copy Label";
  copyOFLabel.backgroundColor = [UIColor greenColor];
  copyOFLabel.frame = CGRectOffset(copyOFLabel.frame, 100, 200);
  //view Added same as self.CustomOutlet expect for the background color set to green
  [self.view addSubview:copyOFLabel];

有没有办法复制 UIViewLabelImage 并保留在 UIViewLabelImage 变量的文本和 img 属性中引用的图像和文本?

您所做的只是创建一个新的 class,设置一些您可以使用 IB 更改的变量。因此,在 class 中的 viewWillAppear 之后,您可以引用该特定对象及其在 IB 中的值(图像、文本等)。现在您已经有了对现有对象的引用,您只需将这些相同的值设置为新创建的对象。如果您希望克隆确切的视图,那么答案就不同了。

newCustomObject.img = self.CustomOutlet.img
// and so on

如果您希望为现有视图创建 "clone",在某些情况下,您可以使用 NSKeyedArchiver 来实现。

id copyOfView = 
[NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:originalView]];

我的建议是简单地使用 IB 作为您自定义的模板 class 然后在创建新实例后在代码中分配图像和文本。