本节重点:
CGRectMake(x,y,width,height); //坐标系&控件大小
tag //唯一标识
- (UIView *)viewWithTag:(NSInteger)tag; // 通过tag获取对应的子控件
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event //触摸事件
- (BOOL)endEditing:(BOOL)force //退出子控件响应的键盘
borderStyle //设置相应键盘的样式
效果:
//
// SJViewController.m
// 02.ButtonCodeDemo
//
// Created by SJ.abnormal on 15-1-29.
// Copyright (c) 2015年 SJ.abnormal. All rights reserved.
//
#import "SJViewController.h"
@interface SJViewController ()
@end
@implementation SJViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[self textFieldWithFrame:CGRectMake(20, 50, 65, 30) andTag:1];
[self textFieldWithFrame:CGRectMake(130, 50, 65, 30) andTag:2];
[self labelWithFrame:CGRectMake(95, 54, 27, 21) andTag:0 andText:@"+"];
[self labelWithFrame:CGRectMake(200, 54, 27, 21) andTag:0 andText:@"="];
[self labelWithFrame:CGRectMake(236, 54, 64, 21) andTag:3 andText:nil];
[self buttonWithFrame:CGRectMake(20, 88, 280, 30) andTag:4 andText:@"计算"];
}
#pragma mark - TextField 生产~
- (void) textFieldWithFrame: (CGRect) frame andTag:(NSUInteger)index{
UITextField *textValue = [[UITextField alloc]initWithFrame:frame]; //设置控件坐标以及大小
textValue.tag = index; //设置位置标识值
textValue.borderStyle = UITextBorderStyleRoundedRect; //设置样式
textValue.keyboardType = UIKeyboardTypeNumberPad; //设置相应的键盘
[self.view addSubview:textValue]; //添加到主视图上
}
#pragma mark - Label 生产~
- (void) labelWithFrame:(CGRect) frame andTag:(NSUInteger)index andText: (NSString *) text {
UILabel *label = [[UILabel alloc]initWithFrame:frame]; //设置控件坐标以及大小
label.text = text; //设置title信息
label.tag = index; //设置位置标识值
[self.view addSubview:label]; //添加到主视图上
if (![label.text isEqualToString: nil] ) {
label.textAlignment = NSTextAlignmentCenter; //对其方式
}
}
#pragma mark - Label 生产~
- (void) buttonWithFrame:(CGRect) frame andTag:(NSUInteger)index andText: (NSString *) text {
UIButton *btn = [[UIButton alloc]initWithFrame:frame]; //设置控件坐标以及大小
[btn setTitle:text forState:UIControlStateNormal]; //设置title信息并设置状态
[btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; //设置title颜色并设置状态
btn.tag = index; //设置位置标识值
btn.layer.cornerRadius = 8.0; //设置圆角度数
btn.layer.borderWidth = 1.0; //设置外边框宽度
[btn addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn]; //添加到主视图上
}
#pragma mark - 按钮点击事件
- (void) buttonClick {
//根据tag获得对应的子视图(控件)
UITextField *textValue1 = (UITextField *)[self.view viewWithTag:1];
UITextField *textValue2 = (UITextField *)[self.view viewWithTag:2];
UILabel *lableResult = (UILabel *)[self.view viewWithTag:3];
NSString *result = [NSString stringWithFormat:@"%d",[textValue1.text intValue] + [textValue2.text intValue]];
lableResult.text = result;
}
#pragma mark - 键盘处理
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
//退出view所有子视图的键盘
[self.view endEditing:YES];
}
@end