ios - 使 Controller 随着 iOS 中 UILabel 中文本的数量而扩展

标签 ios swift uilabel

我对 Swift 和 iOS 还很陌生。我正在努力让事情正常进行,所以请忽略糟糕的用户界面。目前我的文本超出了 Controller 的屏幕,我希望它能够根据文本的长度允许滚动以适应它。

我如何使用 Swift 和 iOS 做到这一点?

Screenshot of problem

最佳答案

首先,您应该将所有 subview (UILabel、UIImage 等)放在UIScrollView 中。

那么,你有两个选择:

  • Springs & Struts:设置所有 subview 的框架后,您可以更新 ScrollView 的 contentSize 属性,以便它允许您滚动。您最好在 viewDidAppear 方法中执行此操作,因为所有帧都在那里有它们的确切值:

    override func viewDidAppear(_ animated: Bool) {
      super.viewDidAppear(animated)
      scrollView.contentSize = CGSize(width: view.frame.width, height: bottomLabel.frame.maxY)
    }
    
  • AutoLayout:使用 Autolayout,您不再需要显式设置 contentSize 属性。只需确保正确设置垂直和宽度约束,这样 AutoLayout 就会自动推断出 contentSize。 scrollView 中的 subview 应按如下方式布局:

       Scroll View
    ----------------
    |   Top Label  |
    | ------------ | v:10pt
    |              |
    |     Image    | image.width = view.width
    |              |
    | ------------ | v:10pt
    | Bottom Label |
    ----------------
    

您可以下载 test project并查看我在 Interface Builder 中设置的约束。

这是我得到的结果:

enter image description here

关于ios - 使 Controller 随着 iOS 中 UILabel 中文本的数量而扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40272329/

相关文章:

Swift - TabBarController - 在运行时决定 segue

ios - UILabel 在设置 minimumScaleFactor 时获取当前比例因子?

ios - EXC_BAD_INSTRUCTION 当我在 Swift 2.0 中设置 UILabel 标题时

ios - Realm - React Native 和 Objective C

ios - 如何移除 UIImagePickerController 的范围 slider ?

swift - App Transport Security 导致 Swift 2.0 应用程序崩溃

ios - 解析,如何通过 PFRelation 进行查找

iphone - 如何检测用户选择不允许用于 iphone 的 MKMapView

iOS 应用程序开始在 4"screen like on 3.5"上运行

objective-c - -[NSString sizeWithFont :] returns different results in release and debug builds