百恒网络
进度条 ProgressView如何实现
  • 百恒服务
  • APP开发
  • 网页案例
  • 网页知识
  • 关于我们
  • 联系我们
  • 进度条 ProgressView如何实现

    2018-09-30 16:28:18 2666
           进度条体现了任务执行的进度,同活动指示器一样,也有消除用户心理等待时间的作用。

           为了模拟真实的任务进度的变化,我们在南昌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])来实现。
    展开分享
    服务
    案例
    首页
    动态
    联系
    咨询