You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift 4中Material Design Snackbar无法正常工作问题求助

Fixing Material Design Snackbar Code for Swift 4

Looks like there are two key issues in your code that are causing it to fail in Swift 4. Let's break them down and fix things step by step:

1. Undefined message variable when setting the action

In your original code, you're trying to assign action to message.action before you've actually declared and initialized the main MDCSnackbarMessage instance (the one you want to show initially). The message inside your actionHandler is a separate, local variable—this isn't the same as the one you're referencing outside the closure.

2. Incorrect logic flow

Your current code tries to create the main snackbar message inside the action's handler, which means the initial snackbar (with the "OK" action) never gets created or shown at all.

Corrected Code

Here's the fixed version that works properly in Swift 4:

// 1. Create the main snackbar message you want to display first
let mainMessage = MDCSnackbarMessage()
mainMessage.text = "Please complete your KYC detail"

// 2. Create and configure the action
let action = MDCSnackbarMessageAction()
action.title = "OK"
action.handler = {
    // This code runs when the user taps "OK"
    // If you want to show a follow-up snackbar here, you can do that:
    let followUpMessage = MDCSnackbarMessage()
    followUpMessage.text = "KYC detail submission process started"
    MDCSnackbarManager.show(followUpMessage)
}

// 3. Attach the action to the main message
mainMessage.action = action

// 4. Show the main snackbar
MDCSnackbarManager.show(mainMessage)

Additional Checks

  • Make sure you've properly integrated the Material Components Snackbar library into your Swift 4 project. If you're using CocoaPods, your Podfile should include:
    pod 'MaterialComponents/Snackbar'
    
    And you've run pod install to get a version compatible with Swift 4 (versions 70+ work reliably).
  • Ensure you've imported the framework at the top of your Swift file:
    import MaterialComponents
    

内容的提问来源于stack exchange,提问作者user9368327

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:35:33