Lou*_*ost 0 cocoa-touch objective-c uiview ios
我想编写一个UIView执行以下操作的自定义:
我想把这个Custom传递UIView给这个iCarousel类:https:
//github.com/nicklockwood/iCarousel
如何UIView使用Objective C和Cocoa 创建自定义?
我开始做以下事情:
CItem.h
#import <UIKit/UIKit.h>
@interface CItem : UIView
{
UIImageView *box;
}
@property (nonatomic, retain) UIImageView * box;
@end
Run Code Online (Sandbox Code Playgroud)
CItem.m
#import "CItem.h"
@implementation CItem
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
- (void)drawRect:(CGRect)rect {
// Drawing code
box = [[UIImageView alloc] initWithFrame:CGRectMake(0,0, 240, 240)];
[box setImage:[UIImage imageNamed:@ "cleaning.png"]];
[self addSubview:box];
}
@end
Run Code Online (Sandbox Code Playgroud)
你不应该添加你addSubview:的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
Run Code Online (Sandbox Code Playgroud)
然后你可以CItem像这样使用:
CItem *subView = [[CItem alloc] initWithFrame:CGRectMake(0, 0, 320, 400)];
[self.view addSubview:subView];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15640 次 |
| 最近记录: |