簡體   English   中英

當UIButton未產生事件時,是否可以使用委托發送消息?

[英]Is it possible to use a delegate to send a message when the event is not produced by a UIButton?

我想知道如何使用委托從名為MotionListener的類向MyViewController發送時鍾消息,但是在將Apple對target-action的解釋轉換為可行命令時遇到了麻煩。

目標動作是一種設計模式,其中,一個對象保存事件發生時向另一個對象發送消息所需的信息。 存儲的信息由兩部分數據組成:一個動作選擇器,它標識要調用的方法;一個目標,它是接收消息的對象。] 1

我毫不費力地將myButton的示例(下)中的解釋(下)應用於myButton使用該fromButtonInSubview將消息發送到名為fromButtonInSubview的目標,只要按下該fromButtonInSubview

        [mySyncButton addTarget:self.delegate
                         action:@selector(fromSyncButtonInSubview:)
               forControlEvents:UIControlEventTouchUpInside];

我假設為了發送不是源自UIButton,的信號UIButton,我仍然需要聲明協議[a] ,為其指定一個屬性[c]並包括一個初始化方法[b]

[一種]

    @protocol SyncDelegate <NSObject>

    -(void)fromSync:(int)clock;

    @end

    @interface MotionListener : NSObject {

    }

並[b]

    - (id) initMotionSensingWith:(float)updateInterval;

[C]

    @property (assign) id<SyncDelegate> delegate;

    @end

並在接口[d]中聲明協議,並在實現[e]中添加目標方法

並[d]

    @interface PlayViewController : UIViewController <SyncDelegate>

並[e]

    - (void)fromSync:(int)clock
    {
        NSLog(@"tick"); // do stuff and show
    }

然后在MyViewController,導入MotionListener [f] ,在實現[g]中對其進行聲明,並定義委托[h]

[F]

    #import "MotionListener.h"

[G]

    MotionListener *sync = [[MotionListener alloc] initMotionSensingWith:(float)updateInterval];

[H]

    sync.delegate = self;

但是,盡管重新閱讀了上面引用的說明,並且在幾次嘗試失敗之后,我仍未編寫一個命令,該命令將從MotionListener發送同步信號到MyViewController. 我知道它將在UIButton示例(如上)中具有action:@selector(fromSync:) addTarget:self.delegateaction:@selector(fromSync:)的效果。 在有人建議使用NSTimer selector,之前NSTimer selector,我已經以50 Hz的頻率對其進行了計時,而同步信號為1 Hz

例如

     [NSTimer scheduledTimerWithTimeInterval:0.02;  // 50 Hz
                                      target:self
                                    selector:@selector(motionRefresh:)
                                    userInfo:nil
                                     repeats:YES];

    - (void)motionRefresh:(id)sender
    {
        count = (count + 1) % 50;  // every 1 second

        if (count == 0 ) 
        {
            // send the sync message here
            // EDIT
            NSLog(@"sending %i", count);
            [self.delegate fromSync:(int)count];
        }
    }

所以我的問題是:使用委托,每次count變為0時如何發送同步消息? 答案可能很尷尬,但如果可以的話,我可以考慮。 謝謝。

我不確定我是否正確理解您的代碼。 但我認為您只需要用對您的代表的呼叫代替// send the sync message here行,例如[self.delegate fromSync:WHATEVERVALUEYOUWANTTOINFORMABOUT];

暫無
暫無

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

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