Huwell
Huwell

Reputation: 79

Will this statement always evaluate to nil in Swift?

open var buttonInit: ((_ index: Int) -> UIButton?)?
...
if let button: UIButton = self.buttonInit?(i) {
    finButton = button
}else {
        let button = UIButton(type: .custom)
        button.setTitleColor(button.tintColor, for: [])
        button.layer.borderColor = button.tintColor.cgColor
        button.layer.borderWidth = 1
        button.layer.cornerRadius = buttonHeight/2
        finButton = button
}

I don't find any function description about buttonInit in AZDialogViewController. Does it mean button: UIButton = self.buttonInit?(i) will always be nil and finButton = button will not be executed?

Upvotes: 1

Views: 65

Answers (2)

tomerpacific
tomerpacific

Reputation: 6475

@Huwell, the documentation in the repository states to initialize the button in the following manner:

dialog.buttonInit = { index in
    //set a custom button only for the first index
    return index == 0 ? HighlightableButton() : nil
}

The button should be part of your DialogViewController.

Upvotes: 0

Sweeper
Sweeper

Reputation: 271625

The latter part of the code you quoted is in the setUpButton method:

fileprivate func setupButton(index i:Int) -> UIButton{
    if buttonHeight == 0 {buttonHeight = CGFloat(Int(deviceHeight * 0.07))}

    let finButton: UIButton

    if let button: UIButton = self.buttonInit?(i) {
        finButton = button
    }else {
        let button = UIButton(type: .custom)
        button.setTitleColor(button.tintColor, for: [])
        button.layer.borderColor = button.tintColor.cgColor
        button.layer.borderWidth = 1
        button.layer.cornerRadius = buttonHeight/2
        finButton = button
    }

This method is called here:

open func addAction(_ action: AZDialogAction){
    actions.append(action)

    if buttonsStackView != nil{
        let button = setupButton(index: actions.count-1)
        self.buttonsStackView.addArrangedSubview(button)
        //button.frame = buttonsStackView.bounds
        button.center = CGPoint(x: buttonsStackView.bounds.midX,y: buttonsStackView.bounds.maxY)
        animateStackView()
    }
}

From this we can see that buttonInit seems to be used to let the user of the library specify what kind of button they want as the action buttons. Another piece of evidence is that buttonInit is declared open, so it is likely that it is the client code who should set this, not the AZDialogViewController.

Plus, the README file showed this usage:

Use custom UIButton sub-class:

dialog.buttonInit = { index in
    //set a custom button only for the first index
    return index == 0 ? HighlightableButton() : nil
}

So to answer your question, the if branch will be executed if you set buttonInit.

Upvotes: 1

Related Questions