2010-05-04 76 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