《精通 iOS 开发》第 04 章学习笔记

调整图像视图的大小

按键:

COMMAND + = 或者菜单选择 Editor ➤ Size to Fit Content

输入完成后关闭键盘

添加以下函数,并关联Did End On Exit事件:

1
2
3
- (IBAction)textFieldDoneEditing:(UITextField *)sender {
[sender resignFirstResponder];
}

通过触摸背景关闭键盘

view所指向的UIView对象所属类改成UIControl,并添加以下函数关联Touch Down事件:

1
2
3
4
- (IBAction)backgroundTap:(id)sender {
[self.nameField resignFirstResponder];
[self.numberField resignFirstResponder];
}

滑动条

代码示例:

1
2
3
4
- (IBAction)sliderChanged:(UISlider *)sender {
int progress = lround(sender.value);
self.sliderLabel.text = [NSString stringWithFormat:@"%d", progress];
}

开关控件

代码示例:

1
2
3
4
5
- (IBAction)switchChanged:(UISwitch *)sender {
BOOL setting = sender.isOn;
[self.leftSwitch setOn:setting animated:YES];
[self.rightSwitch setOn:setting animated:YES];
}

分段控件

代码示例:

1
2
3
4
5
6
7
8
9
10
11
- (IBAction)toggleControls:(UISegmentedControl *)sender {
if (sender.selectedSegmentIndex == 0) {
self.leftSwitch.hidden = NO;
self.rightSwitch.hidden = NO;
self.doSomethingButton.hidden = YES;
} else {
self.leftSwitch.hidden = YES;
self.rightSwitch.hidden = YES;
self.doSomethingButton.hidden = NO;
}
}

操作表单

需要遵从UIActionSheetDelegate协议,代码示例:

1
2
3
4
- (IBAction)buttonPressed:(UIButton *)sender {
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Are you sure?" delegate:self cancelButtonTitle:@"No Way!" destructiveButtonTitle:@"Yes, I'm Sure!" otherButtonTitles:nil];
[actionSheet showInView:self.view];
}

警告视图

需要遵从UIAlertViewDelegate协议,代码示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex {
if (buttonIndex != [actionSheet cancelButtonIndex]) {
NSString *msg = nil;

if ([self.nameField.text length] > 0) {
msg = [NSString stringWithFormat:@"You can breathe easy, %@, everything went OK.", self.nameField.text];
} else {
msg = @"You can breathe easy, eveything went OK.";
}

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Sonmething was done" message:msg delegate:nil cancelButtonTitle:@"Phew!" otherButtonTitles:nil];
[alert show];
}
}