作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我正在尝试返回我在 Xcode 项目中创建的值。 Int 值是在步进器的@IBAction 函数中生成的。
@IBAction func stepper(_ sender: UIStepper) -> Int {
let Number: Int = Int(sender.value)
return Number
print(Number)
系统给我这个错误:“声明@IBAction 的方法必须返回‘Void’(不是‘Int’)”。
最佳答案
@IBAction
是一个内置属性,用于触发将根据用户交互执行某些任务并且不能返回值/对象的方法。您可以做的是触发其他操作,或在操作方法中初始化其他全局/局部变量。
错误 - Methods declared @IBAction must return 'Void' (not 'Int')
只是意味着 IBAction
方法不能返回任何东西,必须返回 void
也就是什么都没有。
根据您对 UIButton
使用步进器值的评论,您可以这样做-
在 View Controller 的类级别声明一个变量
var stepperValue: Int = 0 {
didSet{
// use stepperValue with your UIButton as you want
}
}
然后是@IBAction
-
@IBAction func stepper(_ sender: UIStepper){
stepperValue = Int(sender.value)
}
每次,stepperValue
都在 @IBAction
方法中设置,didSet
观察器中的代码块将触发并且 stepperValue
的当前值可以在 didSet
观察者代码块中访问,以用于您想要的任何逻辑。
或者,您可以简单地将整个 didSet
观察器 block 代码放在 IBAction
方法 stepper
中。
或者,您可以编写另一个方法 func modifyMyButton(_ stepperval: Int)
将您的逻辑放在那里并从 IBAction
方法内部调用此方法。
关于swift - 如何在 swift 3 中从 @IBAction 函数返回 Int 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45599513/
我是一名优秀的程序员,十分优秀!