我正在尝试将文本添加到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")
    }

}

最佳答案

您发布的代码存在很多问题。

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

您的代码有问题:


每当您没有独角兽去世时,都要打开您的可选组件!
您不能直接从Swift 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

关于swift - 在UILabel的新行上添加文本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33703854/

10-14 21:08
查看更多