【问题标题】:How can I increase the y of a label, in swift?如何快速增加标签的 y?
【发布时间】:2015-08-20 11:14:48
【问题描述】:


所以我是 Swift 的新手,我不知道如何从标签中增加 y 值。
我试图在标签中显示用户在输入中键入的一些消息...例如聊天视图。

所以我有这段代码,但它把所有消息都放在另一个之上:

我知道这很混乱,对此我很抱歉。
谢谢!

//my label
    @IBOutlet weak var label: UILabel!
    //my text field
    @IBOutlet weak var textF: UITextField!

@IBAction func buttonPressed(sender: AnyObject) {

        //create a variable(input) to store my text from the TextField
        var input = textF.text
        //put that text in the label
        label.text = input

        var label2 : UILabel = UILabel(frame: CGRectMake(20, 20, 200, 21))
        var isSendMessage: Bool = true {
            didSet {
                if isSendMessage {
                    var input = textF.text
                    label.text = input
                    textF.text = " "
                  //  self.view.label.origin.y += 10

                } else {
                    var input = textF.text
                    label2.text = input
                    textF.text = " "

                }
            }
        }

        label2.center = CGPointMake(160, 284)
        label2.textAlignment = NSTextAlignment.Center
        self.view.addSubview(label2)

        //empty text field
        textF.text = " "

        label2.center = CGPointMake(160, 284)
        label2.textAlignment = NSTextAlignment.Center
        label2.text = input

        //add it to the view
        self.view.addSubview(label2)

    }

【问题讨论】:

    标签: swift label axes


    【解决方案1】:

    试试这个

    不要直接更新 Y 轴,如果你的 Y 值大于屏幕高度,那么标签会离开屏幕。

    试试下面的代码。

    // Taking height and width of the screen
    
    var height = UIScreen.mainScreen().bounds.size.height;
    var width = UIScreen.mainScreen().bounds.size.width; 
    var x = 164.0 // Fixed height of the label
    
    if x < height 
    {
        x += 20.0  // Incrementing height value
        if (height - 20) >= x  // Checking the difference between screen height and x, so it doesn't go beyond the screen.
        {
           label.frame = CGRectMake(20.0, x, 200.0, 21.0)
           self.view.addSubview(label)
        }
        else
        {    
             // Setting default height
             label.frame = CGRectMake(20.0,164.0, 200.0, 21.0)
             self.view.addSubview(label)
        }
    
    }
    

    希望这会有所帮助。

    【讨论】:

    • 嘿,谢谢你的回答,但你不知道有什么方法可以让我增加这些:label.frame = CGRectMake(20, 164, 200, 21),比如:float x = 0; label.frame = CGRectMake(20, 164+x, 200, 21) ; x=x+10?我知道我需要添加一个 for 循环,但我找不到它的语法:164+x
    • 我在“如果 x
    • 我已经更新了答案,请检查是否解决了错误。
    【解决方案2】:

    在快速回答您的问题时,如果您只是想更改 y 轴上的位置,您可以使用 .center 下的属性 .y

    self.yourLabel.center.y = self.yourLabel.center.y + 10
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-29
      • 2017-09-23
      • 1970-01-01
      • 2021-08-18
      • 1970-01-01
      相关资源
      最近更新 更多