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

求助:通过代理模式修改View背景色的Swift代码实现问题

用代理模式修改自定义UIView背景色的实现

下面是完善后的代码,按照Swift规范和需求完成了代理逻辑:

// 遵循Swift大驼峰命名规范定义协议
protocol ViewedDataSource: AnyObject {
    func color(for viewed: Viewed) -> UIColor
}

class Viewed: UIView {
    // 规范属性命名,保持弱引用避免循环引用
    weak var dataSource: ViewedDataSource?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        // 初始化时自动获取并设置背景色
        updateBackgroundColor()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        updateBackgroundColor()
    }
    
    // 核心方法:调用代理获取颜色并设置背景色
    func updateBackgroundColor() {
        // 代理存在则调用方法,否则使用默认白色作为兜底
        let bgColor = dataSource?.color(for: self) ?? .white
        backgroundColor = bgColor
    }
    
    // 代理设置后自动触发背景色更新
    var _dataSource: ViewedDataSource? {
        didSet {
            updateBackgroundColor()
        }
    }
}

class ViewController: UIViewController {
    let tableView = UITableView()
    let viewed = Viewed()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.addSubview(viewed)
        viewed.dataSource = self
        viewed.translatesAutoresizingMaskIntoConstraints = false
        
        NSLayoutConstraint.activate([
            viewed.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 10),
            viewed.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -10),
            viewed.topAnchor.constraint(equalTo: view.topAnchor, constant: 10),
            viewed.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -10),
        ])
        
        viewed.layer.borderWidth = 2
        viewed.layer.borderColor = UIColor.red.cgColor
        viewed.layer.cornerRadius = 10
    }
}

extension ViewController: ViewedDataSource {
    func color(for viewed: Viewed) -> UIColor {
        // 返回需要设置的背景色
        return .magenta
    }
}

关键修改说明:

  • 命名规范:将协议和属性名调整为ViewedDataSource、dataSource,符合Swift代码命名习惯,提升可读性。
  • 触发逻辑:在Viewed初始化方法中调用更新方法,确保视图创建时就加载对应背景色;同时通过属性观察者didSet,在代理赋值完成后自动触发颜色更新。
  • 容错处理:调用代理方法时增加默认颜色兜底,避免因代理未设置导致背景色异常。
  • 语义优化:将协议方法名改为color(for:),贴合Swift API的设计风格,更易理解。

内容的提问来源于stack exchange,提问作者Michael Drammond

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 15:11:21