歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> iPhone-用代碼創建界面(Creating Views from Code)

iPhone-用代碼創建界面(Creating Views from Code)

日期:2017/3/1 10:24:00   编辑:Linux編程

首先新建一個基於視圖的項目,名字為ViewTest;

在ViewTestViewController.m文件viewDidLoad方法中寫上如下代碼:

  1. //創建一個視圖UIView對象,獲取初始化屏幕大小,UIScreen mainScreen該設備的內部屏幕,applicationFrame應用程序的屏幕面積幀點
  2. UIView *view =
  3. [[UIView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame];
  4. //設置背景顏色:灰
  5. view.backgroundColor = [UIColor lightGrayColor];
  6. //創建標簽
  7. CGRect frame = CGRectMake(10, 15, 300, 20);//設置標簽的位置及大小x y width height表示左上角和大小
  8. UILabel *label = [[UILabel alloc] initWithFrame:frame]; //創建並初始化標簽,並且使大小是frame
  9. label.textAlignment = UITextAlignmentCenter; //標簽中文字的對齊方向是居中
  10. label.backgroundColor = [UIColor clearColor]; //標簽背景顏色透明的
  11. label.font = [UIFont fontWithName:@"Verdana" size:20]; //標簽文字的Verdana體20號大小
  12. label.text = @"This is a label";//標簽文字
  13. label.tag = 1000;
  14. //創建text
  15. frame = CGRectMake(10, 70, 300, 30);
  16. UITextField *text=[[UITextField alloc]initWithFrame:frame];
  17. text.backgroundColor=[UIColor whiteColor];
  18. text.text=@"我是任海麗";
  19. //創建按鈕
  20. frame = CGRectMake(10, 120, 300, 50);//按鈕位置大小
  21. UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  22. button.frame = frame;
  23. [button setTitle:@"Click Me, Please!" forState:UIControlStateNormal];
  24. button.backgroundColor = [UIColor clearColor];
  25. button.tag = 2000;
  26. [button addTarget:self
  27. action:@selector(buttonClicked:) //響應事件
  28. forControlEvents:UIControlEventTouchUpInside];
  29. //把標簽,文本和按鈕添加到view視圖裡面
  30. [view addSubview:label];
  31. [view addSubview:button];
  32. [view addSubview:text];
  33. self.view = view;

事件響應方法彈出一個警告框:

  1. -(IBAction) buttonClicked: (id) sender{
  2. UIAlertView *alert = [[UIAlertView alloc]
  3. initWithTitle:@"Action invoked!" message:@"Button clicked!"
  4. delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
  5. [alert show];
  6. }

給出效果圖:

什麼視圖界面,你都可以用代碼寫出來,並設置屬性,當然這個不是簡便的方法,沒有直接拖來的方便,不過這樣做是為了熟悉代碼並知道是怎麼實現的;每個控件都有好多屬性,並且要明白是怎麼用的。學習過程 中不怕麻煩,希望跟大家一塊努力學習!有什麼不好的地方,請多指出!!!

Copyright © Linux教程網 All Rights Reserved