2011-07-04 123 views
2

任何地方在我的应用程序中都有UIButton,我希望它具有特定的背景图像。这个背景图片将永远是一样的。你可以在iPhone应用程序中使用UIButton应用程序吗?

我不想要做的就是调用每个按钮的方法,我把它放入我的用户界面。

我可以通过类别或类似的方式做到这一点吗?

+0

你有没有考虑子类化并从那里做到这一点?界面构建器让你选择类。另外,我看到了一些像Objective-C扩展机制。 “ClassName + Extension”,而ClassName是一个现有的类。不知道这是否适合你。 –

+1

你称之为“扩展”是所谓的类别。 – Moshe

+1

在WWDC 2011关于iOS 5 SDK幻灯片的主题演讲中,出现了“自定义UI”一词。这将回答你的问题。 –

回答

3

您无法通过简单代码(在当前SDK中)更改按钮的全局外观。


,你可以继承你的UIButton。例如:

.h 

@interface MyButton : UIButton 

@end 

--- 

.m 

@implementation MyButton 

// your customization code 

@end 

如果你要插入的UIButton实例,如:

UIButton *button = // init your button 
// customize your button 
[self.view addSubview:button]; 

你必须改变UIButtonMyButton

Mybutton *button= // init your button 
[self.view addSubview:button]; 

中不要忘了你的#import "MyButton.h".m/.hh文件。


编辑:您应该在哪里进行自定义:

@implementation UIButton (MyCategory) 

+ (id)buttonWithFrame:(CGRect)frame { 
    return [[[self alloc] initWithFrame:frame] autorelease]; 
} 

- (id)initWithFrame:(CGRect)frame { 
    if (self = [super initWithFrame:frame]) { 
    // HERE YOU CAN DO SOME CUSTOMIZATION 
    } 
    return self; 
} 

然后,在你的viewController地方:

UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(x, y, width, height)]; 

或:

UIButton *btn = [UIButton buttonWithFrame:CGRectMake(x, y, width, height)]; 
+0

这是我想避免的情况。我更低调的类别路线全球覆盖的UIButtons方法之一。如果按照您的建议,我会在我的实现文件中为每个添加到UI的按钮留下很多UI定位逻辑。在我看来,这是不可接受的。为什么我不能像大多数其他基于MVC的UI技术那样对一个按钮进行蒙皮/模板化?嗯... – jaywayco

+0

当然,你可以创建UIButton类。您必须在您的文件顶部插入'#import' **或**将其插入您的前缀(.pch)文件中。 – akashivskyy

+0

我要在我的类别中重写哪个方法来给按钮一个背景图片? – jaywayco

相关问题