在 PHP 中我会做这样的事情:
function changeBgColor($boxColor,$color)
{
echo '<div id="'. $boxColor .'">'. $color .'</div>';
}
changeBgColor("box1","red");
但是我还没有找到在 Objective-C 中做到这一点的方法
我想用 Objective-C 编写一些代码,并能够调用一个方法来执行该代码。
例如执行这段代码。但是我想在调用方法时更改 boxColor 和 redColor
boxColor.backgroundColor = [UIColor redColor];
最佳答案
你需要这样写一个方法:
- (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]];
或者您可以使用与 PHP 代码相同的方式调用的 C 方法:
void changeBackgroundColorOfElementToColour(NSObject *element, UIColor *color) {
if ([element respondsToSelector:@selector(backgroundColor)]) [element setBackgroundColor:color];
else if ([element respondsToSelector:@selector(tintColor)]) [element setTintColor:color];
}
关于php - 如何创建一个方法,就像我在 php 中所做的那样,但在 Objective-C 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7707203/