2010-10-25 78 views
0

這可能很難解釋。按鈕按下方法位置

基本上我有以下結構到我的項目:

我有一個對象(圖形),其控制其他對象(節點)和(弧)。

一切工作正常,但我發現需要添加按鈕到我的節點對象。這也工作得很好,我有一個NSLog輸出讓我知道哪個節點已被選中等我的問題是,我只想要一次選擇一個節點。我的節點對象的初始化代碼如下:

- (id) initNodeWithData:(NSString *) _label: (int) _xpos: (int) _ypos 
{ 
    if(self = [super init]) 
    { 
    //other variable inits here... 

    [self setButton: [UIButton buttonWithType:UIButtonTypeCustom]]; 

    [button setImage:[UIImage imageNamed:@"node.png"] 
      forState:UIControlStateNormal]; 

    [button setImage:[UIImage imageNamed:@"node.png"] 
      forState:UIControlStateHighlighted]; 

    [button setImage:[UIImage imageNamed:@"nodeSelected.png"] 
      forState:UIControlStateSelected]; 

    [button setImage:[UIImage imageNamed:@"nodeSelected.png"] 
      forState:(UIControlStateHighlighted|UIControlStateSelected)]; 

    [button addTarget:self 
       action:@selector(buttonPressed) 
    forControlEvents:UIControlEventTouchUpInside]; 

} 
return self; 
} 

- (void)buttonPressed 
{ 
    NSLog(@"%@ Pressed", label); 

    if(button.selected == YES) button.selected = NO; 
    else if(button.selected == NO) button.selected = YES; 
} 

因爲我的節點對象是獨立的形式相互我不能(我不認爲我可以無論如何)測試,看是否有其他節點已經在進行選擇之前選擇。

理想我想是這樣的:

- (void)buttonPressed 
{ 
    //Check to see if other nodes are selected 
    //If not, button.selected = yes 
    //else clear other buttons 
    //then select current button 
} 

但我想我需要這個代碼在我的viewController類,那裏有我的所有其他代碼是的,我不知道該怎麼做,因爲我認爲這是全部超出範圍。

對不起,這不是很清楚,很難解釋!

回答

0

您可能有一些存儲當前選定節點的對象。如果用戶按下按鈕,則向該「主」對象發送NSNotification。

MasterObject.h

Node *currentlyActiveNode; 

MasterObject.m

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(activateNode:) name:kNotificationActivateNode object:nil]; 

... 

- (void)activateNode:(NSNotification *)notification { 
    Node *requestingNode = (Node *)[notification.object]; 
    if (requestingNode != currentlyActiveNode) { 
     [currentlyActiveNode deactivate]; 
     currentlyActiveNode = requestingNode; 
     [requestingNode activate]; 
    } 

} 

Node.m

- (void)requestActivation { 
    [[NSNotificationCenter defaultCenter] postNotificationName:name:kNotificationActivateNode object:self]; 
} 

- (void)activate { 
    //Whatever... 
} 
- (void)deactivate { 
    //Whatever... 
} 

你 '圖' 可能是你的主對象...

另類:你甚至可以在每個偵聽「停用」通知的節點中只需要一個NSNotification觀察者。那麼如果有人點擊一個按鈕,你會做什麼只是簡單地發送該通知(節點通過停用偵聽並作出反應),然後激活當前節點。爲了確保這兩個事件不會發生干擾,可以發送一個對發送節點的引用,並且如果發送方==接收方不會停用。

+0

得到它的工作! :)我想我做了你提出的另一種方法,我對客觀C很陌生,所以我不得不做一些關於NSNotification的例子,以及如何使用它,但現在它效果很好! :)非常感謝您的幫助,對您的讚美先生! – 2010-10-26 11:43:49