- 添加文本与编辑框:
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, 200,40)];
label.backgroundColor = [UIColor blueColor];
label.textColor = [UIColor blackColor];
label.text = @"Mylabel";
[label setFont:[UIFont boldSystemFontOfSize:14]];
[self.view addSubview:label];
UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(20, 70, 260, 30)];
textField.borderStyle = UITextBorderStyleRoundedRect;
textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
[textField setFont:[UIFont boldSystemFontOfSize:14]];
textField.placeholder = @"input your text";
textField.delegate = self;
[self.view addSubview:textField];
- 添加ImageView:
-(void) addImageView{
UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(30, 110, 400,300)];
[image setImage:[UIImage imageNamed:@"test.jpg"]];
[image setContentMode:UIViewContentModeScaleAspectFit];
[self.view addSubview:image];
}
这里要注意的是,只把图片放到相关目录下是不行的,需要打开xcode,把图片资源拖到项目结构中才行。
- 旧式对话框
-(void) addAlertView{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"My Alert" message:@"Are you sure?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok", nil];
[alert show];
}
-(void) alertView:(UIAlertView*)alert clickedButtonAtIndex:(NSInteger)buttonIndex{
switch(buttonIndex){
case 0:
NSLog(@"Cancel is clicked.");
break;
case 1:
NSLog(@"Ok is clicked.");
break;
default:
break;
}
}
在viewDidLoad中调用:[self addAlertView]; 同时在头文件中添加代理:
@interface ViewController : UIViewController<UITextFieldDelegate, UIAlertViewDelegate>
4.新式对话框:
-(void) addAlertControler{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"New Alert" message:@"Confirm you operations" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *leftAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
NSLog(@"Cancel is clicked.");
}];
UIAlertAction *rightAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
NSLog(@"Ok is clicked.");
}];
[alertController addAction:leftAction];
[alertController addAction:rightAction];
[self presentViewController:alertController animated:YES completion:nil];
}
presentViewController必须在视图完全加载后才能调用,所以在viewDidLoad中调用
[self addAlertControler];是无效的,不会显示对话框,log中会提示:
Warning: Attempt to present <UIAlertController: 0x7f901d845a00> on <ViewController: 0x7f901cc0bff0> whose view is not in the window hierarchy!
可以在按钮事件中调用:
- (IBAction)onStartBtnClick:(UIButton *)sender {
[_mHello setText:@"Start Clicked"];
[self addAlertControler];
}
结果显示:
来源:CSDN
作者:dingpwen
链接:https://blog.csdn.net/dingpwen/article/details/104374297