有很多與您發佈的代碼問題。
首先,使代碼清晰。我們應該能夠複製代碼並將其粘貼到例如操場中,並且它應該可以工作。有時候這是不可能的,但就你的情況而言。
問題與您的代碼:
- 解開你的自選項目,每次你做的時間不麒麟死!
- 你不能從一個斯威夫特
String
轉換爲Int
直接
這種方法在不導致可選值的方式將一String
到Int
。
// elaborate for extra clarity
let forUsTextNSString = forUsText as NSString
let forUSTextFloat = forUsTextNSString.floatValue
input1 = Int(forUSTextFloat)
這是更新的代碼,它現在編譯:
// stuff I used to test this
var forUs = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
var forThem = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
var us = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
var them = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
// more stuff I used to test this
var input1 : Int = 0
var input2 : Int = 0
var input1total : Int = 0
var input2total : Int = 0
func sign() { // changed to non IB method, don't copy and paste this
// unwrap some optionals (google nil coalescing operator)
let forUsText = forUs.text ?? ""
let forThemText = forThem.text ?? ""
var usText = us.text ?? ""
var themText = them.text ?? ""
// elaborate way to convert String to Int (empty string returns a 0)
let forUsTextNSString = forUsText as NSString
let forUSTextFloat = forUsTextNSString.floatValue
input1 = Int(forUSTextFloat)
// compact method
input1 = Int((forUsText as NSString).floatValue)
input2 = Int((forThemText as NSString).floatValue)
forUs.text = ""
forThem.text = ""
input1total += input1
input2total += input2
us.text = "\(input1total)"
them.text = "\(input2total)"
if (input1total >= 152){
print("you win")
}
if (input2total >= 152){
print("you lose")
}
}
現在來回答這個問題:
UILabel
有一個屬性是用來numberOfLines
\n
插入一行在文本
增加numberOfLines
打破,並與\n
新的文本前添加新的文本。
usText += "\n\(input1total)"
themText += "\n\(input2total)"
// change += 1 to = 2 if that is what you actually need
us.numberOfLines += 1
them.numberOfLines += 1
us.text = usText
them.text = themText
@MohammedAlsaiari沒問題,如果你喜歡答案,請不要忘記加註。 –