2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Use delegate in Swift

Last updated at Posted at 2016-01-13

1 declare a protocol in Class A:

protocol ScrollerBarDelegate: NSObjectProtocol {
    func buttonAtIndexPressed(index: NSInteger)
}

2 decalre a property member in Class A:

Warning: There must be a weak before the property member!!!otherwise, there will be a retain cycle problem.

weak var delegate  : ScrollerBarDelegate?

3 find the place in Class A where you want to trigger the delegate function.

// 按钮触发方法
func funcBtnPressed(sender: UIButton) {
        funcIndex = sender.tag - 1991
        self.delegate?.buttonAtIndexPressed(funcIndex!)
    }

4 conform to Protocol in Class B.

class NewsViewController: UIViewController, ScrollerBarDelegate {
	//
}

5 set the object's delegate in Class B:

bar!.delegate = self

6 complete the function in delegate in Class B:

// MARK: - 协议方法
    func buttonAtIndexPressed(index: NSInteger) {
        //
        print(index)
    }
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?