Can UIView be copied?

后端 未结 6 1584
广开言路
广开言路 2020-11-27 15:02

Simply using this way:

UIView* view2 = [view1 copy]; // view1 existed

This will cause simulator can not launch this app.

Try retai

相关标签:
6条回答
  • 2020-11-27 15:35

    You can make an UIView extension. In example swift snippet below, function copyView returns an AnyObject so you could copy any subclass of an UIView, ie UIImageView. If you want to copy only UIViews you can change the return type to UIView.

    //MARK: - UIView Extensions
    
        extension UIView
        {
           func copyView<T: UIView>() -> T {
                return NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: self)) as! T
           }
        }
    

    Example usage:

    let sourceView = UIView()
    let copiedView = sourceView.copyView()
    
    0 讨论(0)
  • 2020-11-27 15:39

    Your app probably crashes with something like:

     [UIView copyWithZone:]: unrecognized selector sent to instance 0x1c6280
    

    The reason is that UIView does not implement the copying protocol, and therefore there is no copyWithZone selector in UIView.

    0 讨论(0)
  • 2020-11-27 15:40

    You can make method something like this:

    -(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];
    
    }
    

    Then you can set your ivar to the return value and retain it like so:

    myLabel = [[self copyLabelFrom:myOtherLabel] retain];
    
    0 讨论(0)
  • 2020-11-27 15:43

    for swift3.0.1:

    extension UIView{
     func copyView() -> AnyObject{
        return NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: self))! as AnyObject
     }
    }
    
    0 讨论(0)
  • 2020-11-27 15:49

    UIView doesn't implement the NSCoping protocol, see the declaration in UIView.h:

    @interface UIView : UIResponder <NSCoding, UIAppearance, UIAppearanceContainer, UIDynamicItem, UITraitEnvironment, UICoordinateSpace, UIFocusEnvironment>

    So, if we want to have a copy like method, we need to implement the NSCoping protocol in a category or so.

    0 讨论(0)
  • 2020-11-27 15:53

    this might work for you ... archive the view and then unarchive it right after. This should give you a deep copy of a view:

    id copyOfView = 
    [NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:originalView]];
    
    0 讨论(0)
提交回复
热议问题