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

Swift创建UIAlertController弹窗时遇报错:Type has no member 'Style'

解决UIAlertController报错“Type 'UIAlertController' has no member 'Style'”

这个问题我之前也碰到过,大概率是Swift版本与语法不匹配或者缺少必要的框架导入导致的,给你两种针对性的解决方案:

情况1:使用Swift 3及以上版本

这是目前主流的版本,先确保你的文件顶部导入了UIKit框架,然后简化枚举值的写法(上下文会自动推断类型):

import UIKit

class YourViewController: UIViewController {
    @IBAction func showMessage(sender: UIButton) { 
        // 直接用 .alert 替代 UIAlertController.Style.alert
        let alertController = UIAlertController(title: "Welcome to My First App", message: "Hello World", preferredStyle: .alert)
        // 同理,用 .default 替代 UIAlertAction.Style.default
        alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) 
        present(alertController, animated: true, completion: nil)
    }
}

情况2:使用Swift 2版本(旧项目)

如果你的项目还在使用Swift 2,UIKit的样式枚举是独立的,不是嵌套在类中的,代码需要改成这样:

import UIKit

class YourViewController: UIViewController {
    @IBAction func showMessage(sender: UIButton) { 
        let alertController = UIAlertController(title: "Welcome to My First App", message: "Hello World", preferredStyle: .Alert)
        alertController.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) 
        // Swift 2中present方法是presentViewController
        presentViewController(alertController, animated: true, completion: nil)
    }
}

报错原因说明

你遇到的“Type 'UIAlertController' has no member 'Style'”错误,核心原因是:

  • Swift 3对UIKit的API做了大量重构,其中就把原来的独立枚举(比如UIAlertControllerStyle)改成了类的嵌套枚举(UIAlertController.Style);
  • 如果你的项目Swift版本设置和代码语法不匹配(比如用Swift 2的环境写Swift 3的语法),就会出现这个“找不到Style成员”的报错;
  • 另外,如果忘记导入UIKit框架,编译器也无法识别UIAlertController的类型,间接导致类似错误。

最后建议你检查项目的Swift版本设置:点击项目文件 → Build Settings → Swift Language Version,确认版本和你使用的语法一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:42:25