2011-10-09 33 views
0

在PHP中我會做這樣的事情:如何創建一個方法,像我一樣在PHP,但在Objective-C

function changeBgColor($boxColor,$color) 
{ 
    echo '<div id="'. $boxColor .'">'. $color .'</div>'; 
} 

changeBgColor("box1","red"); 

但我還沒有找到一種方法,在Objective-C

做到這一點

我想在Objective-C中寫出一些代碼,並且能夠調用一個方法來執行該代碼。

例如執行此代碼。但我想改變boxColor和redColor當我打電話的方法

boxColor.backgroundColor = [UIColor redColor]; 

回答

2

你需要寫一個像這樣的方法:

- (void) changeBackgroundColorOfElement:(NSObject *) element toColour:(UIColor *) color { 
    if ([element respondsToSelector:@selector(backgroundColor)]) [element setBackgroundColor:color]; 
    else if ([element respondsToSelector:@selector(tintColor)]) [element setTintColor:color]; 
} 

可以由被稱爲:

[self changeBackgroundColorOfElement:myLabel toColour:[UIColor blackColor]]; 

或者你也可以擁有C法,你需要調用相同的方式爲你的PHP代碼:

void changeBackgroundColorOfElementToColour(NSObject *element, UIColor *color) { 
    if ([element respondsToSelector:@selector(backgroundColor)]) [element setBackgroundColor:color]; 
    else if ([element respondsToSelector:@selector(tintColor)]) [element setTintColor:color]; 
} 
0

這裏是如何創建的目標C函數的簡要說明:

- (void) exampleFunction: (int)x y:(int)y 
{ 
do some stuff HERE, changing BG etc 
} 

您可以通過調用這個函數:

[self exampleFunction:*TheValueOfX* y:*TheValueOfY*] 

這是創建一個函數,並使用它的基本途徑,還有其他更復雜的事情,你可能想閱讀有關。

+0

感謝您幫助我更好地理解這一點。 – Syntax

相關問題