【问题标题】:Programmatically add label to Message App in Swift?以编程方式将标签添加到 Swift 中的消息应用程序?
【发布时间】:2016-09-16 22:59:22
【问题描述】:

我知道这是 iOS10 的新功能,但我正在尝试构建一个简单的 ms messageappextension 应用程序,并且我找到的所有教程都通过情节提要添加了它们的标签、按钮等。

我讨厌 autlayout 并且不使用故事板,所以我需要找到如何以编程方式添加元素。这是我尝试过的:

//main label
        pointsLabel.frame = CGRect(x: 0, y: 0, width: view.bounds.width * 0.5, height: view.bounds.height * 0.1)
        pointsLabel.center = CGPoint(x: view.bounds.width * 0.5, y: view.bounds.width * 0.7)
        pointsLabel.textColor = UIColor.red
        pointsLabel.textAlignment = .center
        pointsLabel.text = "Testing 123"
        pointsLabel.font = UIFont(name: "Helvetica", size: screenSize.height * (30/screenSize.height))

        view.addSubview(pointsLabel)

这是 Id 通常制作标签的方式,当 MSMessagesAppViewController 像这样在全视图中时可以使用:

但是当它这样即使center的定位是基于view.bounds的时候,当视图缩小到这里时,标签仍然显示在视图之外:

我发现当大小改变时会调用它,但是即使在这里重置中心也无济于事:

override func willTransition(to presentationStyle: MSMessagesAppPresentationStyle) {
        // Called before the extension transitions to a new presentation style.

        // Use this method to prepare for the change in presentation style.

        print(view.bounds.height)
        pointsLabel.center = CGPoint(x: view.bounds.width * 0.5, y: view.bounds.width * 0.7)
    }

除了在不同高度之间来回切换之外,以编程方式添加标签的正确方法是什么?

【问题讨论】:

    标签: ios swift message swift3 ios10


    【解决方案1】:

    更改您的中心计算以使用y 的超级视图的高度,而不是宽度的一部分:

    pointsLabel.center = CGPoint(x: view.bounds.width * 0.5, y: view.bounds.height * 0.5)
    

    虽然紧凑,但宽度实际上大于高度,因此view.bounds.width * 0.7 将您的标签推离了屏幕。

    【讨论】:

      猜你喜欢
      • 2011-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-17
      • 1970-01-01
      • 2013-03-01
      相关资源
      最近更新 更多