iOS入门-08UITImer和View的位移以及缩放

概述

重点

iOS中定时器的创建和使用;
为了演示每隔一段时间进行一次View的位置变化和缩放;

示例

演示代码

ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
{
    //定时器(成员变量)
    NSTimer *_timerView;
}
//定时器(作为属性)
@property (retain,nonatomic)NSTimer *timerView;

@end
ViewController.m
#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
//关联属性变量和成员变量
@synthesize timerView = _timerView;
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //添加一个开始button
    UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [btn1 setTitle:@"begin" forState:UIControlStateNormal];
    btn1.frame = CGRectMake(100, 100, 100, 40);
    //添加点击事件
    [btn1 addTarget:self action:@selector(pressStart) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn1];
    
    //添加一个停止button
    UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [btn2 setTitle:@"stop" forState:UIControlStateNormal];
    btn2.frame = CGRectMake(100, 200, 100, 40);
    //添加点击事件
    [btn2 addTarget:self action:@selector(pressStop) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn2];
    
    //被移动和缩放的view
    UIView *view = [UIView new];
    view.frame = CGRectMake(100, 300, 80, 80);
    view.backgroundColor = [UIColor blueColor];
    [self.view addSubview:view];
    //这里为了便于下面代码中获取view实例,用tag(和Android中的用法基本一样);
    view.tag = 101;
}

-(void) pressStart
{
    NSLog(@"pressStart");
    //示例化,并开始定时
    //p1:定时器的间隔时间
    //p2:委托处理对象
    //p3:处理事件
    //p4:传递的信息
    //p5:循环模式 YES:循环NO:不循环,只触发一次
    _timerView = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(moveAndScale:) userInfo:@"哈哈哈" repeats:YES];
}
//位移和缩放
-(void) moveAndScale : (NSTimer*) timer
{
    NSLog(@"one second later,name = %@",timer.userInfo);
    //获取view实例
    UIView* view = [self.view viewWithTag:101];
    //控制view的缩放和位置
    view.frame = CGRectMake(view.frame.origin.x+5, view.frame.origin.y+5, view.frame.size.width+5, view.frame.size.height+5);
}

-(void) pressStop{
    NSLog(@"pressStop");
    //停止定时
    [_timerView invalidate];
}

@end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值