iOS 5使用.XIB创建自定义UIButton可重用组件

时间:2012-07-07 09:18:41

标签: ios uibutton storyboard xib reusability

我是iOS开发中的新手,我正在开发一个使用iOS5和Storyboarding的项目。我想创建一个可重用的组件,如按钮,具有自定义视图(按钮内部将有一些图像和标签,它将是一个大按钮),在Storyboard的同一视图中创建它们中的一些。 所以我创建了一个带有UIButton的XIB文件(ItemClothes.xib),里面有一些UIImagesViews和一个UILabel。然后我创建了一个UIButton(UIItemClothes.h和UIItemClothes.m)的子类,其中包含UIImageViews和UILabel组件的属性。

UIItemClothes.h

#import <UIKit/UIKit.h>
#import "SCClothes.h"

@interface UIItemClothes : UIButton

@property (nonatomic, strong) IBOutlet UIImageView *imageClothes;
@property (nonatomic, strong) IBOutlet UIActivityIndicatorView *loadingImage;
@property (nonatomic, strong) IBOutlet UIImageView *seasonIconClothes;
@property (nonatomic, strong) IBOutlet UIImageView *categoryIconClothes;
@property (nonatomic, strong) NSString *idClothes;
@property (strong, nonatomic) IBOutlet UILabel *lblProva;

@end

UIItemClothes.m

#import "UIItemClothes.h"

@implementation UIItemClothes

@synthesize imageClothes = _imageClothes;
@synthesize loadingImage = _loadingImage;
@synthesize seasonIconClothes = _seasonIconClothes;
@synthesize categoryIconClothes = _categoryIconClothes;
@synthesize idClothes = _idClothes;
@synthesize lblProva = _lblProva;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        [self addSubview:[[[NSBundle mainBundle] loadNibNamed:@"ItemClothes" owner:self options:nil] objectAtIndex:0]];
    }
    return self;
}

@end

然后在.XIB文件中,我将UIButton的类设置为UIItemClothes,并在XIB的UI组件和我的类属性之间建立关系。

那么,之后,在Storyboard中,在一个视图的ViewController中,我编写了这段代码:

UIItemClothes *item = [[UIItemClothes alloc] initWithFrame:CGRectMake(0.0, 0.0, 200.0, 200.0)];
item.lblProva.text = @"test!";
[item.categoryIconClothes setImage:iconCategory];
item.seasonIconClothes.image = iconSeason;
[cell addSubview:item];

如您所见,此组件将位于TableViewCell中,其目的是将更多组件(UIItemClothes)放入其中。

问题在于绘制了组件,但任何插座都按照上面的代码设置。

任何人都可以帮助我吗? 谢谢!

1 个答案:

答案 0 :(得分:1)

嗯,问题已经解决了......而不是拥有UIButton的自定义子类,将需要一个包含所有Outlet的ViewController。然后在另一个ViewController(StoryBoard)中初始化这个新的ViewController