gpt4 book ai didi

ios - 在 Swift 中使用 Bool 的 View Controller 扩展

转载 作者:行者123 更新时间:2023-11-28 12:16:50 26 4
gpt4 key购买 nike

我正在尝试对 View Controller 进行扩展。这是带有点击识别器的简单 View 。如果按下一次,背景颜色应该从品红色变为橙色。到下一次推送时,它应该再次变成洋红色。

如果我为具体的 VC 做这件事,比方说 StartVC,它就可以工作。这是代码:

import UIKit

class StartVC: UIViewController {
// bool
var colorChanged = false

override func viewDidLoad() {
super.viewDidLoad()

view.backgroundColor = UIColor.magenta
setMyTouchableView2()
}
}

extension StartVC {
// make touchable view
func setMyTouchableView2() {
let myView = UIImageView(frame: CGRect(x: 100, y: 100, width: 50, height: 50))
myView.backgroundColor = UIColor.yellow

// add gesture recognizer
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(changeColor2(_:)))
myView.addGestureRecognizer(tapGestureRecognizer)
myView.isUserInteractionEnabled = true

view.addSubview(myView)
}

func changeColor2(_ recognizer:UITapGestureRecognizer){
if(colorChanged) {
view.backgroundColor = UIColor.magenta
} else {
view.backgroundColor = UIColor.orange
}

colorChanged = !colorChanged
}
}

但是如果我尝试将此扩展推广到任何 View Controller ,我会遇到以下问题:我无法将我的 boolean 值 (colorChanged) 放入 View Controller 中,因为扩展看不到它。我该如何解决?

代码如下:

import UIKit

class ViewController: UIViewController {
// bool
var colorChanged = false

override func viewDidLoad() {
super.viewDidLoad()

view.backgroundColor = UIColor.magenta
setMyTouchableView()
}
}

extension UIViewController {
// make touchable view
func setMyTouchableView() {
let myView = UIImageView(frame: CGRect(x: 100, y: 100, width: 50, height: 50))
myView.backgroundColor = UIColor.yellow

// add gesture recognizer
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(changeColor(_:)))
myView.addGestureRecognizer(tapGestureRecognizer)
myView.isUserInteractionEnabled = true

view.addSubview(myView)
}

func changeColor(_ recognizer:UITapGestureRecognizer){
if(colorChanged) {
view.backgroundColor = UIColor.magenta
} else {
view.backgroundColor = UIColor.orange
}
}

最佳答案

扩展默认不能有存储属性。但是,如果你真的需要它,你可以通过 objc runtime 创建它

private var associationKey: UInt8 = 111 // Some constant

extension ViewController {
var colorChanged: Bool {
get {
return objc_getAssociatedObject(self, &associationKey) as! Bool
}
set {
objc_setAssociatedObject(self, &associationKey, newValue, .OBJC_ASSOCIATION_ASSIGN)
}
}
}

但是您可能会遇到一个问题,即多个 Controller 会更改此标志。所以你也可以尝试使用协议(protocol)

protocol ColorChangable {
var colorChange: Bool { get set }
}

extension ColorChangable where Self: UIViewController {
func setMyTouchableView {
// Your logic
}
}

class ViewController: UIViewController {
var colorChange: Bool

func viewDidLoad() {
self.viewDidLoad()

setMyTouchableView()
}
}

extension ViewController: ColorChangable {}

关于ios - 在 Swift 中使用 Bool 的 View Controller 扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46210633/

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