进度条 ProgressView如何实现

       进度条体现了任务执行的进度,同活动指示器一样,也有消除用户心理等待时间的作用。

       为了模拟真实的任务进度的变化,我们在南昌APP开发过程中可以引入定时器(NSTimer)。定时器继承于NSObject类,可在特定的时间间隔后向某对象发出消息。

       打开Interface Builder,实现按钮的动作和进度条的输出口,ViewController中的相关代码如下:

       class ViewController: UIViewController {

        @IBOutlet weak var myProgressView: UIProgressView!

        @IBAction func downloadProgress(sender: AnyObject) {

        }

       } 

       //ViewController.m文件

       @interface ViewController ()

       ……

       @property (weak, nonatomic) IBOutlet UIProgressView *myProgressView;

       - (IBAction)downloadProgress:(id)sender;

       @end 

       其中Download按钮的实现代码如下:

       class ViewController: UIViewController {

       @IBOutlet weak var myProgressView: UIProgressView!

       var myTimer: NSTimer!

       @IBAction func downloadProgress(sender: AnyObject) {

       myTimer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self,

       selector: "download", userInfo: nil, repeats: true) ①

       }

       func download() { ②

       self.myProgressView.progress = self.myProgressView.progress + 0.1

       if (self.myProgressView.progress == 1.0) {

       myTimer.invalidate() //停止定时器

       var alert : UIAlertView = UIAlertView(title: "download completed!",

       message: "", delegate: nil, cancelButtonTitle: "OK") ③

       alert.show()

       }

       }

       } 

       - (IBAction)downloadProgress:(id)sender

       {

       myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0

       target:self

       selector:@selector(download)

       userInfo:nil

       repeats:YES]; ①

       }

       -(void)download{ ②

       self.myProgressView.progress=self.myProgressView.progress+0.1;

       if (self.myProgressView.progress==1.0) {

       [myTimer invalidate]; //停止定时器

       UIAlertView*alert=[[UIAlertView alloc]initWithTitle:@"download completed!"

       message:@""

       delegate:nil

       cancelButtonTitle:@"OK"

       otherButtonTitles: nil]; ③

       [alert show];

       }

       }

       第①行代码中使用了NSTimer类。NSTimer是定时器类,它的静态方法是scheduledTimerWithTimeInterval:

       target:selector:userInfo:repeats:,可以在给定的时间间隔调用指定的方法,其中第一个参数用于设定间隔时间,第二个参数target用于指定发送消息给哪个对象,第三个参数selector指定要调用的方法名,相当于一个函数指针,第四个参数userInfo可以给消息发送参数,第五个参数repeats表示是否重复。

       第②行代码的download方法是定时器调用的方法,在定时器完成任务后一定要停止它,这可以通过语句myTimer.invalidate()(Objective-C版中是[myTimer invalidate])来实现。

提供全面的搜索引擎优化学习交流,专注网站优化和搜索引擎营销推广服务。用专业的SEO技术为企业网站提升关键词排名,让你的网站不仅满足用户体验还要适合搜索引擎优化规则。
易速网站优化公司 » 进度条 ProgressView如何实现
享更多特权,立即登录下载海量资源
喜欢我嘛?喜欢就按“ctrl+D”收藏我吧!♡