我有一個名為 GaugeView 的類,它允許我構建一個“儀表”,在其中顯示一條線,該線根據當前分數 (CURRENT_POINTS) 和最高分數 (MAX_POINTS) 之間的比率進行著色。
此類,目前僅用于應用程式的一個部分,兩個變數保存在 UserDefaults 中。
現在我希望在應用程式的其他部分使用這個類,我想使用基于使用這個類的 ViewController 的不同資料,而不是 MAX_POINTS 和 CURRENT_POINTS。
我怎樣才能做到這一點?我試圖復制該類,但 Xcode 給了我一個編譯時錯誤,更準確地說是“架構 arm64 的錯誤 4 重復符號”。
我想到了干預這部分代碼:
- (void) drawRect:(CGRect)rect {
CGContextRef ctx = UIGraphicsGetCurrentContext();
if(ctx == nil) return;
double maxPoints = [[NSUserDefaults standardUserDefaults] integerForKey:MAX_POINTS];
double currentPoints = [[NSUserDefaults standardUserDefaults] integerForKey:CURRENT_POINTS];
orangeSegmentValue = (currentPoints/maxPoints)*270.00;
[self drawBackground:rect context:ctx];
}
放置一個“如果”,但我不知道如何設定它。這是我的想法:
- (void) drawRect:(CGRect)rect {
CGContextRef ctx = UIGraphicsGetCurrentContext();
if(ctx == nil) return;
if (Im_in_ViewController_A) {
//use data from View Controller A
} else {
//do this
double maxPoints = [[NSUserDefaults standardUserDefaults] integerForKey:MAX_POINTS];
double currentPoints = [[NSUserDefaults standardUserDefaults] integerForKey:CURRENT_POINTS];
}
orangeSegmentValue = (currentPoints/maxPoints)*270.00;
[self drawBackground:rect context:ctx];
}
有什么幫助嗎?謝謝
uj5u.com熱心網友回復:
您可以使用協議來獲取具有默認實作的類中的 2 個值:
@protocole GaugeViewDelegate {
@required
- (double) currentPoints();
- (double) maxPoints();
@end
@interface GaugeView : UIView, GaugeViewDelegate
@property GaugeViewDelegate delegate;
…
@implementation GaugeView
- (id) init() {
…
_delegate = self;
..,
}
- (double) currentPoints() {
// get value from user default
return [[NSUserDefaults standardUserDefaults] integerForKey:CURRENT_POINTS] * 1.0;
}
- (double) maxPoints() {
return [[NSUserDefaults standardUserDefaults] integerForKey:MAX_POINTS];
}
- (void) drawRect:(CGRect)rect {
CGContextRef ctx = UIGraphicsGetCurrentContext();
if(ctx == nil) return;
double maxPoints = [delegate maxPoints];
double currentPoints = [delegate currentPoints];
orangeSegmentValue = (currentPoints/maxPoints)*270.00;
[self drawBackground:rect context:ctx];
}
…
然后將其他視圖控制器宣告為實作協議并添加兩個可以作為屬性的方法:
@interface oneViewVontroller : UIViewCintriller, GaugeViewDelagate
@property double maxPoints;
@property double currentPoints;
…
@implementation oneViewVontroller
- (void) viewDidLoad() {
…
_maxPoints = 1000.0
_currentPoints = 0.0;
…
}
你也可以只實作這兩種方法。
uj5u.com熱心網友回復:
按照建議嘗試不同的解決方案后,我只是在 GaugeView.h 中宣告了 2 個屬性
@property double maxPoints;
@property double currentPoints;
并在方法中使用它們
- (void) drawRect:(CGRect)rect {
CGContextRef ctx = UIGraphicsGetCurrentContext();
if(ctx == nil) return;
orangeSegmentValue = (_currentPoints/_maxPoints)*270.00;
[self drawBackground:rect context:ctx];
}
并且無需將它們保存到 NSUserDefaults 中,因此我可以在需要時將它們分配到使用 GaugeView 的類中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/366719.html
