在Swift中,该语句的值是否始终为nil?

时间:2018-11-30 07:12:08

标签: swift user-interface button

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
}

AZDialogViewController中找不到有关 buttonInit 的任何功能描述。这是否意味着 button:UIButton = self.buttonInit?(i)始终为零,而 finButton = button 将不会执行?

2 个答案:

答案 0 :(得分:1)

您引用的代码的后半部分在std::streambuf方法中:

setUpButton

此方法在这里调用:

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
    }

由此我们可以看到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() } } 似乎是用来让库的用户指定他们想要哪种按钮作为操作按钮。另一个证据是buttonInit被声明为buttonInit,因此应该由客户端代码设置而不是open

此外,{{3}}文件显示了这种用法:

  

使用自定义UIButton子类:

AZDialogViewController

因此,为回答您的问题,如果设置了dialog.buttonInit = { index in //set a custom button only for the first index return index == 0 ? HighlightableButton() : nil } ,将执行if分支。

答案 1 :(得分:0)

@Huwell, 存储库中的文档说明以以下方式初始化按钮:

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

该按钮应该是DialogViewController的一部分。