这才是你真正想要的。
主要我们可以使用自定义.xib来加载自定义UITableViewCell, UICollectionViewCell和自定义PopUp
- 将自定义 .xib 加载为
UITableViewCell
像这样创建一对自定义 .xib 及其类文件。(例如 CustomCell.Swift 和 CustomCell.xib)
新建文件.. -> 用户界面 -> 查看 -> 保存为您的类名“CustomCell” -> 创建
现在您将获得带有 UIView 子类的 .xib 文件,但我们需要一个 UITableViewCell 那么我们该怎么办?我们删除那个 UIView 文件并添加一个UITableViewCell 并给出类名CustomCell 和标识符。 (Command + Shift + L) UITableView 并根据您的项目要求拖放到 xib 窗口和设计单元格。
现在我们将移动到代码部分并在 ViewContoller 类文件中初始化 .xib 并将其加载到 UITableView 中。
我们将从我们的包中获取单元格,并将单元格注册到 UITableView。
UITableView.register(UINib(nibName: "CustomCell", bundle: nil), forCellReuseIdentifier: "CustomCell")
- 使用此配置并加载
cellForRowAt indexPath 中的单元格
let cell : CustomCell = self.(YourTableView).dequeueReusableCell(withIdentifier: "CustomCell") as! CustomCell
return cell
- 将自定义 .xib 加载为
UICollectionViewCell
注意:重复上述步骤,将UITableViewCell替换为UICollectionViewCell并像这样注册UICollectionViewCell
self.collectionView.register(UINib(nibName: "CollectoinCustCell", bundle: nil), forCellWithReuseIdentifier: "CollectoinCustCell")
- 使用此配置并加载
cellForRowAt indexPath 中的单元格
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell : CollectoinCustCell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectoinCustCell", forIndexPath: indexPath) as! CollectoinCustCell
return cell
}
自定义视图作为弹出窗口(以上述问题的适当答案结束)
创建一对 xib 文件,此时您不必从 .xib 文件中删除 UIView。
从您的捆绑包中获取 xib,例如:
let CustomXIB = Bundle.main.loadNibNamed("CustomXIB", owner: nil, options: nil)?.first as? CustomXIB
在viewWillAppear中定义你的xib文件的框架
CustomXIB?.frame = UIScreen.main.bounds
创建 appDelegate 实例文件以在主窗口中添加 xib 文件:您的 AppDelegate 将如下所示。
var AppInstance: AppDelegate!
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate
{
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool
{
AppInstance = self
}
}
- 并将您的 customXIB 添加到一些 IBAction 上,例如:
AppInstance.window?.addSubview(self.CustomXIB!)
self.CustomXIB?.removeFromSuperview()