2021 年在 swift 中复制/克隆 UIView?

问题描述 投票:0回答:1

有一些类似的问题,但答案使用了已弃用的方法。

我的解决方案与他们类似,但采用现代方法:

func copyObject<T: UIView>() throws -> T? {
        let data = try NSKeyedArchiver.archivedData(withRootObject:self, requiringSecureCoding:false)
        return try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? T
    }

问题是它不能完全工作(似乎其他问题答案也有同样的问题)-子视图之一具有未复制的角半径。如何解决这个问题?

ios swift uiview copy clone
1个回答
0
投票

答案取决于您的

UIView
包含的内容。例如,假设您想要克隆默认的
UILabel
。在 2024 年(截至撰写本文时我正在玩 Xcode 15.3 RC2),您必须在解档时在
NSKeyedUnarchiver.unarchivedObject(ofClasses:from:)
中定义一些类。下面的代码至少应该可以工作。

func clone(label: UILabel) throws -> UILabel? {
  let archive = try NSKeyedArchiver.archivedData(withRootObject: label, requiringSecureCoding: false)
  // Define 3 classes here for UILabel, otherwise it throws an error
  return try NSKeyedUnarchiver.unarchivedObject(ofClasses: [UILabel.self, UIColor.self, UIFont.self], from: archive) as? UILabel
}

我通过典型的

lldb
调试得到了这一点,我不确定我们是否能找到一种通用方法来克隆
any UIView
最终。

希望这有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.