4

I know that a view can only be a subview of one superview, so is it possible to duplicate the UILabel so I don't have to copy the set-up code or write a function to create it?

4 Answers 4

12

No, the UILabel class doesn't implement the NSCopying protocol. If you want to add the same view to all your views, maybe subclassing your custom view would be the best way to go.

0

As said by @starkhalo, UILabel does not conform to NSCopying. so you can not use copy method with UILabel.

Iphone docs for NSObject clearly says -

NSObject does not itself support the NSCopying protocol. Subclasses must support the protocol and implement the copyWithZone: method.

-1

You can set up a separate XIB just for that label, and call [[NSBundle mainBundle] loadNibNamed:@"LabelNib" owner:self options:nil]; Set up the file owner of that nib to your delegate class, and make the proper connections. Now you can add the label to your view as many times as needed, and modify each one (with a for loop, for example).

-13

The copy method is available by anything that inherits from NSObject so my first port of call would just be to try

UILabel *second = [first copy];

However, this might not work 100% as expected, some UILabel propertiesmight not get copied how you want. If not, you could try using NSCoding methods - encode the object and then decode it into a new object?

It might just be easier to do it by hand though ;)

Sam

2
  • 1
    As stated this does not work. You'll get an error like this: 'NSInvalidArgumentException', reason: '-[UILabel copyWithZone:]: unrecognized selector sent to instance 0x7b959d0'
    – Besi
    Oct 27, 2011 at 12:07
  • Yep, lots of objects do that and it's really annoying:( My next suggestion to the OP was going to be create category that implements NSCopying and produces a new UILabel :) Unfortunately before then someone had provided a different answer that solved the problem :) Oct 27, 2011 at 14:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.