如何创建Storyboard中UIView的多个独立实例?
解决Storyboard视图创建多个独立实例的问题
你遇到的其实是引用类型的典型“坑”——你数组里的三个someview根本不是三个独立的视图,它们全都是指向同一个对象的引用!所以不管你改哪个,本质上都是在修改内存里的同一个视图,自然所有的都会跟着变。
要创建真正独立的实例,你得每次从Storyboard里重新加载一个新的视图副本,具体步骤如下:
第一步:给Storyboard里的视图设置可重用标识
首先,在Storyboard里找到你设计的那个视图,建议把它放到一个单独的ViewController里(这个ViewController的整个view就是你要重用的视图),然后选中这个ViewController,在右侧的Identity Inspector里,给它设置一个唯一的Storyboard ID,比如ReusableCustomViewVC。
第二步:通过代码循环创建独立实例
接下来用代码每次实例化这个ViewController,它的view就是一个全新的独立视图了。示例代码如下:
// 初始化空数组用来存独立视图 var testArray: [UIView] = [] // 获取你的Storyboard实例(替换成你的Storyboard名字,比如"Main") let mainStoryboard = UIStoryboard(name: "Main", bundle: .main) // 循环创建7个实例 for _ in 0..<7 { // 实例化对应的ViewController guard let reusableVC = mainStoryboard.instantiateViewController(withIdentifier: "ReusableCustomViewVC") else { continue } // 获取新的视图实例 let newView = reusableVC.view // 这里可以给新视图设置frame、添加到父视图等操作 newView.frame = CGRect(x: 0, y: 0, width: 150, height: 80) // 添加到数组 testArray.append(newView) }
进阶优化:封装成自定义视图的类方法
如果你的视图有自定义类,还可以把加载逻辑封装到类里,让代码更简洁:
class CustomReusableView: UIView { static func loadNewInstance() -> CustomReusableView? { let storyboard = UIStoryboard(name: "Main", bundle: .main) guard let vc = storyboard.instantiateViewController(withIdentifier: "ReusableCustomViewVC") as? UIViewController else { return nil } return vc.view as? CustomReusableView } }
之后创建实例就更简单了:
var testArray: [CustomReusableView] = [] for _ in 0..<7 { if let newView = CustomReusableView.loadNewInstance() { testArray.append(newView) } }
这样创建出来的每个视图都是完全独立的对象,修改其中任何一个的属性,其他的都不会受到影响啦!
内容的提问来源于stack exchange,提问作者Quintus
相关产品推荐
相关产品推荐

