2015-11-14 65 views
0

我试图将文本添加到UILabel的新行,现在它替换了当前的文本。在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

有很多与您发布的代码问题。

首先,使代码清晰。我们应该能够复制代码并将其粘贴到例如操场中,并且它应该可以工作。有时候这是不可能的,但就你的情况而言。

问题与您的代码:

  • 解开你的自选项目,每次你做的时间不麒麟死!
  • 你不能从一个斯威夫特String转换为Int直接

这种方法在不导致可选值的方式将一StringInt

// 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 
+0

@MohammedAlsaiari没问题,如果你喜欢答案,请不要忘记加注。 –