你可以在没有子类化的情况下做到这一点——通过创建一个类别(在 Objective-C 中做事的首选方式)。使用类别,您可以为对象提供自定义方法,而无需对其进行子类化。您不能(轻松地)提供自定义属性,但在您的情况下,这不相关。
使用类别
这是您的类别头文件的外观:
// UIButton+StyledButton.h
#import <UIKit/UIKit.h>
@interface UIButton (StyledButton)
- (void) styleButton;
@end
然后在实现文件中:
//
// UIButton+StyledButton.m
//
#import "UIButton+StyledButton.h"
@implementation UIButton (StyledButton)
- (void) styleButton {
//style your button properties here
self.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
}
('self'指的是按钮对象,它也获取了你在类中编写的自定义方法。)
要使用它,#import "UIButton+StyledButton.h" 然后你可以做这种事情......
on viewDidLoad {
[super viewDidLoad];
UIButton* myButton = [[UIButton alloc] initWithFrame:myFrame];
[myButton styleButton];
}
使用子类
子类等效项如下所示:
头文件...
// MyCustomButton.h
#import <UIKit/UIKit.h>
@interface MyCustomButton : UIButton
- (id)initWithCoder:(NSCoder *)coder;
- (id)initWithFrame:(CGRect)frame;
@end
实现文件...
// MyCustomButton.m
#import "MyCustomButton.h"
@implementation MyCustomButton
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self styleButton];
}
return self;
}
- (id)initWithCoder:(NSCoder *)coder
{
self = [super initWithCoder:coder];
if (self) {
[self styleButton];
}
return self;
}
- (void) styleButton {
//style your button properties here
self.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
}
您提供了两个初始化方法 - initWithFrame 是在代码中分配/初始化对象时调用的方法; initWithCoder 是系统在从情节提要或 xib 加载对象时调用的 init 方法。
要在代码中创建您的自定义按钮之一,您可以像处理任何其他对象一样分配/初始化:
MyCustomButton* button = [[MyCustomButton alloc] initWithFrame:buttonFrame];
您不会也分配/初始化超类实例,这是由子类中的initWithFrame: 方法在调用[super initWithFrame:frame] 时完成的。 self 指的是您的自定义子类实例,但包括它的超类中的所有(公共)属性和方法 - 除非您在子类中实现了覆盖。
要在情节提要/xib 中使用您的子类按钮,只需拖出一个常规按钮,然后在 Identity Inspector 中将其类型设置为您的自定义按钮类。当按钮从 storyboard/xib 加载到视图中时,会自动调用 initWithCoder 方法。
更新
从您的 cmets 看来,您似乎仍然存在一些困惑,所以这里有一些高度压缩的去混淆注释...
除非你真的知道你在做什么,否则不要继承 UINavigationController。很少需要。
navController 界面上的按钮是它所包含的 viewController 的属性。查找UIViewController 的navigationItem 属性(类似地 - 在UIToolbar 的情况下 - 视图控制器具有toolbarItems 属性)。这允许导航控制器具有上下文感知能力。
假设我的示例中的“viewDidLoad”位于常规UIViewController 中。我的示例也是常规UIBUtton 上的一个类别,它与UIBarButtonItem 没有正式关系。
在尝试使用UIBarButtonItem(不继承自UIButton)之前,请先尝试让 UIButton 类别与常规 ViewController 一起使用。
UIBarbuttonItem 没有initWithFrame,因为组织栏的东西(UINavigationBar 或UIToolbar)——在这种情况下是导航控制器——负责它的最终大小和定位。 viewController 控制 barButtonItems 的相对顺序,以及它们是出现在左侧还是右侧,以及它的内容和(某些方面)的外观,但其余的取决于 NavController。