所以我有这个自定义导航栏项目,我想将其子类化并在其他ViewControllers
中使用。问题是,条形码项目还有一个observer
,我想在ViewDidAppear
添加observer
并移除ViewDidDisappear
上的subclass
。如何observer
条形项目和ViewControllers
输出。并将其包含在我的每个ViewController
中,而不是复制代码?
当前代码:
在每个override func viewWillAppear(animated: Bool) {
if (!observingDefaults) {
defaults.addObserver(self, forKeyPath: Constants.General.kConnectedToPC, options: NSKeyValueObservingOptions(), context: nil)
observingDefaults = true
}
self.updateConnectionIcon()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
if (observingDefaults) {
defaults.removeObserver(self, forKeyPath: Constants.General.kConnectedToPC)
observingDefaults = false
}
}
中:
extension UIViewController {
func updateConnectionIcon() {
self.navigationItem.rightBarButtonItem = nil
let isConnected = NSUserDefaults.standardUserDefaults().boolForKey(Constants.General.kConnectedToPC)
let button = UIButton()
if isConnected {
button.setImage(UIImage(named: "BluetoothEnabled")?.imageWithRenderingMode(.AlwaysTemplate), forState: UIControlState.Normal)
} else {
button.setImage(UIImage(named: "BluetoothDisabled")?.imageWithRenderingMode(.AlwaysTemplate), forState: UIControlState.Normal)
}
button.frame = CGRectMake(0, 0, 23, 31)
button.tintColor = UIColor.whiteColor()
button.userInteractionEnabled = false
let barButton = UIBarButtonItem(customView: button)
self.navigationItem.rightBarButtonItem = barButton
}
}
导航条项目的扩展名:
ViewController
无论如何,我可以将上半部分添加到底部代码,这样我就可以在每个class PercentageFile:
def __init__(self, filename):
self.size = os.stat(filename)[6]
self.f = open(filename,"r")
self.i = self.f.tell()
def __enter__(self):
return self
def readline(self):
data = self.f.readline()
self.i = self.f.tell()
return data
def __iter__(self):
return self
def __next__(self):
data = self.f.readline()
if self.i == self.f.tell():
raise StopIteration
self.i = self.f.tell()
return data
def read(self, size=None):
if size is None:
self.i = self.size
return self.f.read()
data = self.f.read(size)
self.i = self.f.tell()
return data
@property
def percentage(self):
return float(self.i) / self.size * 100.0
def __exit__(self, exc_type, exc_value, traceback):
self.f.close()
中调用updateConnectionIcon()?
答案 0 :(得分:2)
不是将观察者放在每个viewController中,而是创建一个BaseClase并将其保留在那里并继承所有需要这些观察者的类。这有道理吗?