You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

UIKit中如何创建可修改控制器界面的闭包?

实现带配置闭包的控制器Present方法

你可以给UIViewController添加一个扩展方法,让你在present控制器的同时,直接通过闭包完成对控制器UI和属性的配置,无需额外定义中间变量,让代码更紧凑规整。

实现代码

extension UIViewController {
    func present<T: UIViewController>(_ viewController: T, animated: Bool = true, completion: (() -> Void)? = nil, configure: (T) -> Void) {
        // 先执行配置闭包修改控制器
        configure(viewController)
        // 再present控制器
        present(viewController, animated: animated, completion: completion)
    }
}

使用示例

完全符合你想要的写法:

// Presents controller
present(MyController()) {
    // Updates Controller
    $0.backgroundColor = .red
    $0.delegate = self
}

对比传统写法

传统写法需要先定义控制器变量,分散配置逻辑:

let controller = MyController()
// Updates Controller
controller.backgroundColor = .red
controller.delegate = self

// Presents controller
present(controller, animated: true)

这种闭包配置的方式把控制器的实例化、配置、present操作整合在同一个调用中,消除了冗余的中间变量,让相关逻辑高度集中,代码结构更简洁易读。

内容的提问来源于stack exchange,提问作者Santiago Padilla

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 20:18:15