在数独中需要用到的控件有UILable、UITextFeild以及UIButton;将需要的控件拖到画板上,然后在ViewController.h文件中与事件联系在一起。 动作是为了响应一个时间,返回类型,IBAction UIButton的事件添加为action 自动生成-(IBAction) FinshGame: (id) sender; 为了能访问控件,我们定义了输出口,关键字为IBOutlet 自动生成 @property (weak, nonatomic) IBOutlet UILabel *GameName;
在ViewController.h中的代码实现是:
@interface ViewController : UIViewController @property (weak, nonatomic) IBOutlet UITextField *num1; @property (weak, nonatomic) IBOutlet UITextField *num2; @property (weak, nonatomic) IBOutlet UITextField *num3; @property (weak, nonatomic) IBOutlet UITextField *num4; @property (weak, nonatomic) IBOutlet UITextField *num5; @property (weak, nonatomic) IBOutlet UITextField *num6; @property (weak, nonatomic) IBOutlet UITextField *num7; @property (weak, nonatomic) IBOutlet UITextField *num8; @property (weak, nonatomic) IBOutlet UITextField *num9; @property (nonatomic, strong) NSMutableArray *finshArray; @property (weak, nonatomic) IBOutlet UILabel *result; - (IBAction)FinshGame:(id)sender; - (IBAction)replayGame:(id)sender; @end
在ViewController.m中的代码实现是:
- (IBAction)FinshGame:(id)sender { NSArray *textArray=@[@[_num1,_num2,_num3],@[_num4,_num5,_num6],@[_num7,_num8,_num9]]; int flag=1; for (int i=0; i<[textArray count]; i++) { for (int j=0; j<3; j++) { // NSLog(@"%@",MutableNumber[i][j]); UITextField *viewText=textArray[i][j]; if (![viewText.text isEqualToString:_finshArray[i][j]]) { flag=0; } } } if (flag==1) { _result.text=@"恭喜你,赢了!"; } else { _result.text=@"你输了!"; } } - (IBAction)replayGame:(id)sender { NSArray *numberArray=@[@[@"1",@"2",@"3"],@[@"2",@"3",@"1"],@[@"3",@"1",@"2"]]; NSMutableArray *MutableNumber=[NSMutableArray arrayWithArray:numberArray]; NSArray *tempArray=@[]; int rand1=arc4random()%2; int rand2=arc4random()%2; tempArray=MutableNumber[rand1]; MutableNumber[rand1]=MutableNumber[rand2]; MutableNumber[rand2]=tempArray; NSArray *textArray=@[_num1,_num2,_num3,_num4,_num5,_num6,_num7,_num8,_num9]; int flag=0; for (int i=0; i<[MutableNumber count]; i++) { for (int j=0; j<3; j++) { UITextField *viewText=textArray[flag]; viewText.text=MutableNumber[i][j]; flag++; } } _finshArray=MutableNumber; for (int n=0; n<4; n++) { int tempFlag=arc4random()%9; UITextField *viewText1=textArray[tempFlag]; viewText1.text=@""; } }