我正在尝试将文字添加到UILabel
的新行,现在它会替换当前文本。
UILabel
? UILabel
添加新行?@IBAction func sign(sender: AnyObject) {
if (ForUs.text == ""){
input1 = 0
} else{
input1 = Int((ForUs.text)!)!
}
if (ForThem.text == ""){
input2 = 0
} else {
input2 = Int((ForThem.text)!)!
}
ForUs.text?.removeAll()
ForThem.text?.removeAll()
input1total += input1
input2total += input2
Us.text = "\(input1total)"
Them.text = "\(input2total)"
if ( input1total >= 152){
print("you win")
}
if (input2total >= 152){
print("you lose")
}
}
答案 0 :(得分:0)
您发布的代码存在很多问题。
首先,明确代码。我们应该能够复制代码,粘贴它,例如游乐场,它应该工作。有时这是不可能的,但在你的情况下它是。
您的代码问题:
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