Simplemente usando de esta manera:
UIView* view2 = [view1 copy]; // view1 existed
Esto hará que el simulador no pueda iniciar esta aplicación.
Intenta retener
UIView* view2 = [view1 retain]; // view1 existed
// modify view2 frame etc
Cualquier modificación view2se aplicará a view1, entiendo que view2comparten la misma memoria con view1.
¿Por qué no se UIViewpuede copiar? ¿Cuál es la razón?
ios
objective-c
uiview
copy
Para descanso
fuente
fuente

esto podría funcionar para usted ... archive la vista y luego desarchive inmediatamente después. Esto debería darle una copia profunda de una vista:
id copyOfView = [NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:originalView]];fuente
UIImageViews :(Puede crear una extensión UIView. En el siguiente fragmento de código rápido de ejemplo, la función copyView devuelve un objeto AnyObject para que pueda copiar cualquier subclase de un UIView, es decir , UIImageView. Si desea copiar solo UIViews, puede cambiar el tipo de retorno a UIView.
//MARK: - UIView Extensions extension UIView { func copyView<T: UIView>() -> T { return NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: self)) as! T } }Uso de ejemplo:
let sourceView = UIView() let copiedView = sourceView.copyView()fuente
para swift3.0.1:
extension UIView{ func copyView() -> AnyObject{ return NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: self))! as AnyObject } }fuente
UIViewno implementa elNSCopingprotocolo, vea la declaración en UIView.h :@interface UIView : UIResponder <NSCoding, UIAppearance, UIAppearanceContainer, UIDynamicItem, UITraitEnvironment, UICoordinateSpace, UIFocusEnvironment>Entonces, si queremos tener un
copymétodo similar, necesitamos implementar elNSCopingprotocolo en una categoría más o menos.fuente
Puedes hacer que el método sea algo como esto:
-(UILabel*)copyLabelFrom:(UILabel*)label{ //add whatever needs to be copied UILabel *newLabel = [[UILabel alloc]initWithFrame:label.frame]; newLabel.backgroundColor = label.backgroundColor; newLabel.textColor = label.textColor; newLabel.textAlignment = label.textAlignment; newLabel.text = label.text; newLabel.font = label.font; return [newLabel autorelease]; }Luego puede establecer su ivar en el valor de retorno y retenerlo así:
myLabel = [[self copyLabelFrom:myOtherLabel] retain];fuente