• 从零开始学iPhone开发(2)——控件的使用


    这一节我们开始学习iOS中简单控件的使用。

    在iOS编程中,简单的控件有很多,其中主要的用的多的有:

    UILabel,UIButton,UISegmentedControl, UITextField, UISlider, UISwitch

    等。现在我们来学习使用这些控件。

    1.首先我们学习在xib上来使用,

    如下图,在工程中新建一个TestComponentViewController,并且选中With xib复选框,如下图

    然后点击TestComponentViewController.xib文件,拖动右下角的控件到界面上(类似VS),如下图常用控件都可以直接拖进去。

    现在我们需要对这些控件进行操作,该如何做呢?这里演示UILabel和UIButton的操作,其它操作类似。

    如下图,我们首先在TestComponentViewController.h文件中定义需要操作的控件成员变量(以IBOutlet修饰),并且定义点击UIButton后触发的消息函数(以IBAction来修饰),代码如下:

    #import <UIKit/UIKit.h>
    
    @interface TestComponentViewController : UIViewController{
        IBOutlet UILabel *_label;
        IBOutlet UIButton *_button;
    }
    
    -(IBAction)buttonClicked:(id)sender;
    
    @end
    

     现在我们需要把代码和xib中的拖到界面上的控件连接对应起来,这样代码操作的就是xib上面的控件。如下图:

    对UILabel和成员变量_label进行连接的做法,类似UIButton和成员变量_button可进行同样的连接,消息函数和_button也可以进行同样的连接。

    然后我们在TestComponentViewController.m中实现-(IBAction)buttonClicked:(id)sender;消息,实现代码如下:

    -(IBAction)buttonClicked:(id)sender
    {
        _label.text = @"New Clicked Message Text";
        [_button setTitle:@"Clicked" forState:UIControlStateNormal];
    }

    现在我们可以运行程序了,运行效果如下:

                             (1) 点击Button前                                                 (2) 点击Button后 

    现在我们学会了简单的UILabel和UIButton的使用。其它的空间使用类似,但是有些函数触发不太一样。UIButton默认触发函数事件是TouchupInside,而UISegmentedControl默认是ValudeChanged。


    2.我们使用纯代码来进行编辑
    我们新建
    TestMenuComponentViewController,不添加xib文件。我们在viewDidLoad函数中来实现这些控件的新建和初始化代码如下:
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        // Do any additional setup after loading the view.
        _button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        _button.frame = CGRectMake(35.0, 57.0, 100.0, 44.0);
        [_button setTitle:@"Button" forState:UIControlStateNormal];
    
        
        _label = [[UILabel alloc] initWithFrame:CGRectMake(35.0, 20.0, 245.0, 21.0)];
        _label.text = @"Label";
        
        [_button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
        
        [self.view addSubview:_label];
        [self.view addSubview:_button];
    }

    运行效果如下:



    项目源代码链接:

    http://115.com/lb/5lbfksd5#
    TeachingProject.zip


    115网盘礼包码:5lbfksd5

  • 相关阅读:
    百度多图上传
    uploadify--上传文件控件
    JS获取时间
    CSS选择器
    派大星博客的美化之路
    百度地图--JS版
    css实现元素下出现横线动画
    盒模型显隐、定位与流式布局思想
    css进度条
    Build Sharepoint 2013 Farm
  • 原文地址:https://www.cnblogs.com/yaoliang11/p/3227528.html
Copyright © 2020-2023  润新知