gpt4 book ai didi

ios - 在许多 View Controller 上使用委托(delegate)和协议(protocol)快速更改主题

转载 作者:行者123 更新时间:2023-11-28 13:33:01 25 4
gpt4 key购买 nike

我第一次尝试使用委托(delegate)和协议(protocol)。

我想在多个 View Controller 中更改主题。

然后在任何具有更改主题协议(protocol)的 Controller 上

当我现在转到这个 Controller 时,我希望主题是新的,但它是旧的。

我不会从主题 Controller 转到它们发生变化的地方


我的代码

protocol ThemeDelegate: class {
func changeTheme(theme: UIColor)
}


class FirstController: UICollectionViewController, UICollectionViewDelegateFlowLayout, ThemeDelegate {

var newTheme: UIColor = .red

func changeTheme(theme: UIColor) {
newTheme = theme
}

override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = newTheme
}
}

ThemeController {

weak var themeDelegate: ThemeDelegate?

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let theme = .blue
themeDelegate?.changeTheme(theme: theme)
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: themeCellId, for: indexPath) as! ThemeCell
cell.themeImageView.image = UIImage(named: "theme cell image")
return cell
}
}

this is order

image2

最佳答案

我会尽量让它变得简单:-

1) 首先,声明一个协议(protocol):-

protocol ThemeDelegate{
func changeTheme(theme: String, fontColor: UIColor, alpha: CGFloat)
}

2) 在你的 ThemeController 中有一个该协议(protocol)的变量:

open var themeDelegate: ThemeDelegate? = nil

3) 通过 themeDelegate 调用委托(delegate)函数:-(到这一步你已经做对了)

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
themeDelegate?.changeTheme(theme: theme, fontColor: fontColor, alpha: alpha)
}

4) 您需要使您的 AnyController 符合委托(delegate),例如 yourThemeControllerInstance.delegate = self 并且您也已经这样做了。

它不起作用,因为您已经声明了 ThemeController 的一个新实例,并且已经使 AnyController 成为该新实例的委托(delegate),该实例应该具有相同的旧主题:

override func viewDidLoad() {
let themeController = ThemeController() // This is a new instance which you have created, so gets initialised with old theme. You have made your class to be the delegate of this instance
themeController.themeDelegate = self
}

为了让您的委托(delegate)按预期工作,您需要在更改主题时使用相同的 ThemeController 实例

关于ios - 在许多 View Controller 上使用委托(delegate)和协议(protocol)快速更改主题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57069036/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com