首页 > 解决方案 > 更改按钮标题颜色时出现 11db 错误 EmptyDataSet_Swift)

问题描述

我目前在我的应用程序中使用“EmptyDataSet_Swift”来处理空状态,但我不知道如何正确使用 buttonTitle 函数来更改按钮的颜色。这是它的参考:

/// Asks the data source for the title to be used for the specified button state.
/// The dataset uses a fixed font style by default, if no attributes are set. If you want a different font style, return a attributed string.
func buttonTitle(forEmptyDataSet scrollView: UIScrollView, for state: UIControl.State) -> NSAttributedString?

我能够做的是更改文本的标题,但是当我更改前景色时,我收到一个错误。这是我的代码:

 func buttonTitle(forEmptyDataSet scrollView: UIScrollView, for state: UIControl.State) -> NSAttributedString? {
    let buttonTitle = "Add a Project"
    let buttonTitleAttributes: [NSAttributedString.Key: Any] = [
        .font: UIFont(name: "HelveticaNeue-Bold", size: 14),
        .foregroundColor: UIColor.green.cgColor
    ]
    let attributedButtonTitle = NSAttributedString(string: buttonTitle, attributes: buttonTitleAttributes)
    return attributedButtonTitle

}

这是我收到的错误的屏幕截图: 在此处输入图像描述

EmptyDataSet_Swift:https ://github.com/Xiaoye220/EmptyDataSet-Swift

标签: iosswiftxcodebuttonnsattributedstring

解决方案


弄清楚了:

 func buttonTitle(forEmptyDataSet scrollView: UIScrollView, for state: UIControl.State) -> NSAttributedString? {
    var text: String?
    var font: UIFont?
    var textColor: UIColor?
    
    text = "Add Project";
    font = UIFont(name: "HelveticaNeue-Bold", size: 18)
    textColor = UIColor(hexColor: state == .normal ? "53cf9f" : "53cf9f" )

    if text == nil {
        return nil
    }
    var attributes: [NSAttributedString.Key: Any] = [:]
    
    if font != nil {
        attributes[NSAttributedString.Key.font] = font!
    }
    
    if textColor != nil {
        attributes[NSAttributedString.Key.foregroundColor] = textColor
    }
    
    return NSAttributedString.init(string: text!, attributes: attributes)
}

推荐阅读