你不应该添加你的addSubview:
in drawRect:
。请参阅此方法的讨论:
讨论
此方法的默认实现什么也不做。使用原生绘图技术(如 Core Graphics 和 UIKit)来绘制其视图内容的子类应覆盖此方法并在那里实现其绘图代码。如果您的视图以其他方式设置其内容,则无需重写此方法。例如,如果您的视图仅显示背景颜色,或者您的视图直接使用底层图层对象设置其内容,则不需要覆盖此方法。同样,如果您的视图使用 OpenGL ES 进行绘图,则不应覆盖此方法。
如果您不使用 xib 文件,您CItem
可以将代码添加到initWithFrame:
.
//CItem.h
#import <UIKit/UIKit.h>
@interface CItem : UIView
- (void)flip;
@end
// CItem.m
#import "CItem.h"
@interface CItem()
@property (assign, nonatomic) BOOL displayingPrimary;
@property (strong, nonatomic) UIImageView *primaryView;
@property (strong, nonatomic) UIImageView *secondaryView;
@end
@implementation CItem
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
_primaryView = [[UIImageView alloc] initWithFrame:frame];
[_primaryView setImage:[UIImage imageNamed:@ "cleaning.jpg"]];
[self addSubview:_primaryView];
_secondaryView = [[UIImageView alloc] initWithFrame:frame];
[_secondaryView setImage:[UIImage imageNamed:@ "adding.jpg"]];
[self addSubview:_secondaryView];
}
return self;
}
- (void)flip
{
[UIView transitionFromView:(self.displayingPrimary ? self.primaryView : self.secondaryView)
toView:(self.displayingPrimary ? self.secondaryView : self.primaryView)
duration:1.0
options:(self.displayingPrimary ? UIViewAnimationOptionTransitionFlipFromRight :
UIViewAnimationOptionTransitionFlipFromLeft) | UIViewAnimationOptionShowHideTransitionViews
completion:^(BOOL finished) {
if (finished) {
self.displayingPrimary = !self.displayingPrimary;
}
}];
}
@end
然后你可以CItem
像这样使用:
CItem *subView = [[CItem alloc] initWithFrame:CGRectMake(0, 0, 320, 400)];
[self.view addSubview:subView];