2015-11-14 61 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沒問題,如果你喜歡答案,請不要忘記加註。 –