簡體   English   中英

從子視圖Objective-c檢索值

[英]Retrieving values from subviews Objective-c

我創建了一個UIView的子類,它是一個旋轉輪。 這個輪子是另一個UIView的一部分,它在右上角有一個圖像。 轉動滾輪時,在touchMoved功能中返回最右側的項目(其編號)。 我需要在轉動子視圖時自動更改父圖像(返回數字時)

假設我在子視圖中有這個數字,我怎么能將它返回到父視圖,或者從子視圖中更改圖像(在父UIView中)?

謝謝

首先,創建一個協議,該協議定義要在超級視圖中調用的方法:

@protocol wheelViewDelegate {
   -(void)doSomething;
}

您的superview需要實現此協議:

@interface superView:UIView<wheelViewDelegate> {
...
}
...
@end

另外,您顯然需要實現doSomething方法。

包含輪子的UIView需要是UIView的子類並保存委托,如下所示:

@interface WheelView : UIView {
id<wheelViewDelegate> delegate;
...
}
@propery (nonatomic, assign) id<wheelViewDelegate> delegate;
...
@end

不要忘記@synthesize id; 在你的實施中。

現在,您可以從子視圖中調用doSomething視圖中的doSomething

[self.delegate doSomething];

編輯:

好吧,我認為這很明顯,但是,當然,您需要像這樣設置委托:

//In your superView:
WheelView* wv = [WheelView initSomeHow];
wv.delegate = self;

Phlibbo提到的委托方法是執行此操作的一種方法。 由於您的自定義視圖子類更像是帶有值的控件,因此我將UIControl而不是UIView並使用UIControlEventValueChanged事件。

在您的自定義子類中,通知值已更改(可能在您的touchedEnded:withEvent:

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [self sendActionsForControlEvents:UIControlEventValueChanged];
}

現在觀察控制器中的值變化,讓控制器在另一個視圖中更新圖像。

- (void) viewDidLoad {
    [wheelControl addTarget:self action:@selector(wheelValueChanged:) forControlEvents:UIControlEventValueChanged];
}

- (void) wheelValueChanged:(id)sender {
    // update your image based on the wheel value of sender (wheelControl in this case).
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM