我开发了一个小的Swift代码,显示了一些人的喜欢。所以我有一个基于while循环的代码,将喜欢的数量合计为一个。然后,我创建了一个显示短语的函数,包括该循环的结果。现在,在我的视图控制器中,我想在我创建的标签上运行该显示功能,以便最终在屏幕上显示所有时间。但是,我似乎无法理解如何在标签上运行显示功能并让它显示而不是我先点击按钮的结果。请记住,这是我编写的第二天,只有Java基本语法的经验。
这是第一个代码
import UIKit
class likesObject: NSObject {
// This is where I created the loop to solve for the total amount of likes
func complimentsLikeTotal() -> Void {
let monthlyLikes = [20, 15, 13, 32, 14, 38]
var totalLikes = 0
var runTotal = 0
while runTotal < monthlyLikes.count {
totalLikes += monthlyLikes[runTotal]
print(totalLikes)
runTotal += 1
}
}
/*
This is where I created the function to return how many all time likes there are in a phrase
I want to use this function in the viewcontroller code on the label
*/
func display() -> String {
return "\(complimentsLikeTotal) all time likes"
}
}
这是视图控制器代码
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var inputLikesLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Here is where I don't know what to do with display and how to link it with the label
self.inputLikesLabel.text = display
}
}
答案 0 :(得分:1)
可能正在寻找这样的事情:(请根据惯例将课程名称以资本开头)
var likesObject = LikesObject()
likesObject.complimentsLikeTotal()
let display = likesObject.display()
self.inputLikesLabel.text = display
我假设LikesObject类还定义了一些全局变量来保存数据。
P.S。在swift中,没有必要显式地声明void返回值,如果省略它,则编译器暗示void。