2010-05-04 48 views
0

我有一个视图,只有一个按钮UIButton。第一次点击按钮将在按钮上方绘制一个正方形,第二次将用圆形替换正方形。初学者iPhone控制器问题

我需要一些编写控制器代码的帮助。请引导我走向正确的道路。谢谢

+0

你能告诉我们你试过了什么吗? – Tim 2010-05-04 03:12:17

回答

0

设计一个形状类。将您的形状添加为UIImageViews。点击每个按钮,在点击时更改Alpha。

@interface Shape: UIView { 
    UIImageView *square; 
    UIimageView *circle; 
    BOOL isSquare; 
} 

@property (nonatomic, retain) UIImageView *square; 
@property (nonatomic, retain) UIImageView *circle; 
@property BOOL isSquare; 

-(void)changeShape; 
@end 

@implementation Shape 
@synthesize square; 
@synthesize circle; 
@synthesize isSquare; 

- (id)initWithFrame:(CGRect)frame { 

if ((self = [super initWithFrame:frame])) { 

    self.frame = //frame size. 


    //assume a square image exists. 
    square = [[UIImageView alloc] initWithImage: [UIImage imageNamed: @"square.png"]]; 
    square.alpha = 1.0; 
    [self addSubview: square]; 

    //assume a circle image exists. 
    circle = [[UIImageView alloc] initWithImage: [UIImage imageNamed: @"circle.png"]]; 
    circle.alpha = 0.0; 
    [self addSubview: circle]; 

    isSquare = YES; 

    } 
    return self; 
} 

-(void)changeShape { 

if (isSquare == YES) { 
    square.alpha = 0.0; 
    cirle.alpha = 1.0; 
    isSquare = NO; 
} 

if (isSquare == NO) { 
    circle.alpha = 0.0; 
    square.alpha = 1.0; 
    isSquare = YES; 
} 


} 

//rls memory as necessary. 
@end 

////////////////////////////////在您的视图控制器类。

实例化您的类并将其添加为子视图。

@class Shape; 

@interface ShapeViewController : UIViewController { 
    Shape *shape; 
} 

@property (nonatomic, retain) Shape *shape; 


-(IBAction)clickedButton:(id)sender; 

@end 

////////

#import "Shape.h" 
@implementation ShapeViewController; 

//add your shape as a subview in viewDidLoad: 

-(IBAction)clickedButton:(id)sender { 
    [shape changeShape]; 
} 
@end 

这应该给你一个很好的基本实现思路。基本上,你设计一个班,然后每次点击改变它的形状。它应该从方形/圆形/方形/圆形交替。希望有所帮助。

+0

感谢您的回答。我试图运行代码,并得到这个错误消息“不兼容类型的'setFrame'的参数1这一行:square = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@”square.png“]]; – Besha 2010-05-04 06:11:44

+0

你设置一个框架?self.frame需要一个CGRect结构。 – 2010-05-04 16:18:59

+0

你能简单描述一下如何做到这一点吗?谢谢。还有,viewDidLoad和initWithFrame有什么不同? – Besha 2010-05-04 19:24:10