【问题标题】:11db error when changing button title color EmptyDataSet_Swift)更改按钮标题颜色时出现 11db 错误 EmptyDataSet_Swift)
【发布时间】:2021-07-15 17:25:21
【问题描述】:

我目前在我的应用程序中使用“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

【问题讨论】:

    标签: ios swift xcode button nsattributedstring


    【解决方案1】:

    想通了:

     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)
    }
    

    【讨论】:

    • if font != nil { attributes[NSAttributedString.Key.font] = font! },这是旧的 Swift。而是:if let font = UIFont(name: "HelveticaNeue-Bold", size: 18) { attributes[.font] = font }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-07
    • 2023-02-21
    相关资源
    最近更新 更多