您的位置:首页 > 产品设计 > UI/UE

IOS开发-代码创建UI控件并修改控件属性(代码创建UIButton、UILabel)

2015-05-05 15:42 776 查看
一. 概述:

在IOS开发的界面搭建步骤中,Storyboard中的所有操作都可以通过代码实现,Storyboard的实质是xcode根据Storyboard文件的描述帮我们转换为代码,总之代码是万能的,那么什么时候适合使用Storyboard什么时候使用代码创建按钮呢?一般一个界面中位置是固定不变的,程序运行时一直是可见的这样一般用Storyboard即可,但是有些控件需要做某些操作时才会出现,这时候一般就会使用代码创建。

二. 代码创建控件的步骤

1. 使用要用控件的类创建控件对象,比如创建按钮控件:

// 创建默认类型的按钮
UIButton *delete = [[UIButton alloc] init];
// 创建custom类型按钮
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];


2.设置控件的各种属性,包括位置尺寸、显示的文字、背景颜色等等,总之在sotryBoard中可以设置的属性代码完全可以做到:

+ (UIColor *)blackColor;      // 0.0 white
+ (UIColor *)darkGrayColor;   // 0.333 white
+ (UIColor *)lightGrayColor;  // 0.667 white
+ (UIColor *)whiteColor;      // 1.0 white
+ (UIColor *)grayColor;       // 0.5 white
+ (UIColor *)redColor;        // 1.0, 0.0, 0.0 RGB
+ (UIColor *)greenColor;      // 0.0, 1.0, 0.0 RGB
+ (UIColor *)blueColor;       // 0.0, 0.0, 1.0 RGB
+ (UIColor *)cyanColor;       // 0.0, 1.0, 1.0 RGB
+ (UIColor *)yellowColor;     // 1.0, 1.0, 0.0 RGB
+ (UIColor *)magentaColor;    // 1.0, 0.0, 1.0 RGB
+ (UIColor *)orangeColor;     // 1.0, 0.5, 0.0 RGB
+ (UIColor *)purpleColor;     // 0.5, 0.0, 0.5 RGB
+ (UIColor *)brownColor;      // 0.6, 0.4, 0.2 RGB
+ (UIColor *)clearColor;      // 0.0 white, 0.0 alpha


View Code
2)将控件背景颜色设为绿色的示例

UIView *newView = [[UIView alloc] init];
// 设置背景颜色为绿色
newView.backgroundColor = [UIColor greenColor];


2.UIViewController的 - (void)viewDidLoad方法使用

1》 这是控制器的一个方法
2》当控制器的view创建完毕的时候会调用一次,仅此一次。
一般在此方法中加载app的数据。
3. 随机数的获取

// 产生一个随机数
u_int32_t    arc4random(void);
// 产生小于所传参数的随机数
u_int32_t arc4random_uniform(u_int32_t /*upper_bound*/)


4.控制器的宽度和高度的获取

开发中为了适应不同的屏幕尺寸要经常使用当前屏幕的宽度和高度,可通过UIView的frame.size得到

// 宽度获取
CGFloat width = self.view.frame.size.width;
// 高度获取
CGFloat height = self.view.frame.size.height;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: