当我向具有默认参数的objc函数发送#selector函数调用时,如何使其工作

时间:2019-01-11 18:44:09

标签: swift

事件在多个位置调用#selector函数,并且需要不同的参数值。我在这里使用的参数之一是默认参数(Bool)。但是,在调用setBar函数时,默认始终为false。

我在做什么错?

// the to be called function, done by a target action event from a segmentedControl.changeEvent or by a DispatchQueue delay or during a viewDidAppear.

@objc func setBar(segmentedControl: UISegmentedControl, animated: Bool = true) {
    func adjustBar() {
        self.bar!.frame.origin.x = (self.segmentedControl!.frame.width / CGFloat(self.segmentedControl!.numberOfSegments)) * CGFloat(self.segmentedControl!.selectedSegmentIndex)
    }
    if animated == true {
        UIView.animate(withDuration: 0.2) {
            adjustBar()
        } }
    else {
        adjustBar()
    }
}


// the code that set the target & action for the segmentedControl
segmentedControl!.addTarget(self, action: #selector(setBar), for:UIControl.Event.valueChanged)


// code called when setting the index by code
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(100)) {
        self.setBar(segmentedControl: self.segmentedControl!, animated: false)
    }

除默认值外,其他所有功能均可用。有什么建议可以解决这个问题吗?

谢谢您的回答。 但是如果我使用true like;

  DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(100)) {
        self.setBar(segmentedControl: self.segmentedControl!, animated: true)
    }

然后起作用。因此,阅读提到的文章,签名有效

或者,如果我改变/转过头来,说出误用的东西,它就会起作用。

@objc func setBar(segmentedControl: UISegmentedControl, notAnimated : Bool = false) {
    func adjustBar() {
        self.bar!.frame.origin.x = (self.segmentedControl!.frame.width / CGFloat(self.segmentedControl!.numberOfSegments)) * CGFloat(self.segmentedControl!.selectedSegmentIndex)
    }

    print("notAnimated = \(notAnimated)")
    if notAnimated == false {
        UIView.animate(withDuration: 0.2) {
            adjustBar()
        } }
    else {
        adjustBar()
    }
}
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(100)) {
        self.setBar(segmentedControl: self.segmentedControl!, notAnimated: true)
    }

0 个答案:

没有答案