2017-02-15 46 views
4

我有一个UIViewControllerUIView(作为组件)。以下是该组件的代码。面向协议的Swift中的自定义组件编程

class ProcessingProgressIndicator: UIView { 

    var progressView: UIProgressView! 

    func changeProgress(_ progress: Float) { 
     progressView.progress = progress 
    } 
} 

所以我在多个控制器使用该组件。所以当我需要改变我在控制器中使用的进度值。

myProgressView.changeProgress(progress) 

因此,为了使组件面向协议,我在下面添加了代码。

protocol ProgressUpdateable { 
    func updateWith(progressView: ProcessingProgressIndicator,progress: Float) 
} 

extension ProgressUpdateable { 
    func updateWith(progressView: ProcessingProgressIndicator,progress: Float) { 
     // Method gets called and can change progress 
    } 
} 

所以从我的控制,我把方法如下

updateWith(progressView: progressView,progress: progressData.progress) 

这是我如何使它协议为主。

所以我的问题是:它是否是正确的执行方式?

我需要传递progressView的对象我可以摆脱它吗?

+0

您需要制作自定义组件,遵守协议,然后使用它来调用该方法。混乱在哪里? –

+0

你能描述如何使它符合协议吗? –

+0

@parth Adroja确认您的第一个控制器通过向其代表确认了解第二个控制器。 –

回答

4

因此,为了使组件面向协议,我在下面添加了代码。

protocol ProgressUpdateable { 
    func updateWith(progressView: ProcessingProgressIndicator,progress: Float) 
} 

extension ProgressUpdateable { 
    func updateWith(progressView: ProcessingProgressIndicator,progress: Float) { 
     // Method gets called and can change progress 
    } 
} 
So from my controller, I call method as below 

updateWith(progressView: progressView,progress: progressData.progress) 

这就是我如何使它面向协议。

0

你在说什么是使用授权协议。

This是苹果公司的文档,编辑得非常好,我可以说,他们在那里解释关于协议的所有内容。全部阅读,但跳到代表团会议,看看你到底在找什么。

0

如果您关注的是通过委托来实现它(还有其他的选择,比如在一个封闭的参数返回进度值),它应该是类似于:

protocol CustomComponentDelegate { 
    func customComponentProgressDidStartUpdate(component: UIView, progressValue: Float) 
} 

class CustomComponent: UIView { 

    var delegate:CustomComponentDelegate? 

    // ... 

    func updateProgressValue(progress: Float) { 
     progressView.progress = progress/100.0 
     progressLabel.text = "\(Int(progress)) %" 

     delegate?.customComponentProgressDidStartUpdate(component: self, progressValue: progressView.progress) 
     // or you might want to send (progress/100.0) instead of (progressView.progress) 
    } 

    // ... 
} 

我认为您的自定义组件是UIView的一个子类,它不应该有所作为。

用法:

class ViewController: UIViewController, CustomComponentDelegate { 
    //... 

    // or it might be an IBOutlet 
    var customComponent: CustomComponent? 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     //... 

     customComponent?.delegate = self 
    } 

    func customComponentProgressDidStartUpdate(component: UIView, progressValue: Float) { 
     // do whatever you want with the returned values 
    } 
} 

注意,如果updateProgressValue范围更新进度值作为实时的,然后customComponentProgressDidStartUpdate委托方法也应为实时执行。

此外,你可能想要检查this question/answer以了解更多关于这里发生了什么。

希望这有助于。

+0

其实,这不是我要找的,你的情况就像控制器从进度中获取价值。我想要做的就像控制器将进度值发送到使用协议的组件,那里的组件将做相关的事情。你的情况实际上是反过来然后我想要的。 –

+0

那么,你的意思是'updateProgressValue'存在于控制器中吗?并且你想将它发送到customView? –

+0

它在组件中,我使用它作为object.method,但我正在寻找其他方式来做到这一点。 –