【问题标题】:UITextView Height AdjustmentUITextView 高度调整
【发布时间】:2018-03-04 09:16:37
【问题描述】:

我正在尝试创建一个可以容纳一些大文本的 ViewController。我使用了UILabel,但由于文本可能很长,所以它不起作用。尝试切换到UITextView,但我遇到了一些问题。

我正在使用ScrollView,因为顶部有一个图像,底部有一个按钮。所以我不会在 UITextView 本身内滚动。我已禁用它。

我想根据文字长度自动调整文字高度。所以它可以滚动图像、按钮等。就像应用程序 Instapaper、Medium、Pocket 等一样。

我已经尝试了 StackOverflow 上的所有代码和解决方案,但它们要么不起作用,要么是 Objective-C。

故事板结构: View Controller -> View -> ScrollView -> Image, TextView, Button

class ViewController: UIViewController {

  @IBOutlet weak var textView: UITextView!
  var theContent = fromClass.text

  override func viewDidLoad() {
    super.viewDidLoad()
    textView.text = theContent
  }
}

【问题讨论】:

  • 你需要在滚动视图中添加一个视图作为 Image、TextView 和按钮的容器。新添加的视图必须具有相同的宽度,滚动视图的超级视图的高度。
  • @yerpy ,好的,我已经做到了,但是如何让 TextView 根据内容调整高度?
  • 您需要跟踪字符串的大小并根据它调整文本视图的高度。

标签: swift uikit uitextview


【解决方案1】:

有几种方法可以改变UITextView的大小

extension String {

    func bounds(approximated width: CGFloat, approximated height: CGFloat, font: UIFont) -> CGRect {
        let size = CGSize(width: width, height: height)
        let attribs = [NSAttributedStringKey.font: font]

        return NSString(string: self).boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: attribs, context: nil)
    }
}

approximated width = 你的UITextView 的宽度我认为它将是你不会改变的静态值。

approximated height = UITextView 的最小高度。

返回文本输入帧的方法。从中获取 height 属性,并根据它的大小改变UITextView 的大小。

如果不满意,你可以换一种方式。

func heightOfString(_ attributes: [NSAttributedKeyString : Any]) -> CGFloat {
    let size = self.size(withAttributes: attributes)
    return size.height
}

与上面的用法相同。

【讨论】:

    【解决方案2】:

    将您的视图层次结构调整为以下视图层次结构:

    View Controller -> View -> ScrollView -> View1 -> Image, UILabel, Button

    1- 给 view1 top-left-bottom-right 约束,并将它的中心 X 对齐到它的父视图

    2- 在 View1 的顶部添加UIImageView 并为其赋予上下左右约束和固定高度约束。

    3- 添加一个UILabel 并将其设置为图像的顶部约束和其超级视图的右下角约束。

    使UILabel行数=0

    内容不应该是可滚动的。

    请注意:在您的情况下;你不需要UITextView

    如果你想使用UITextView:

    1- 为UITextView 添加高度约束并将插座连接到它 调用:constTextViewHeight

    let textViewContentHeight = textView.contentSize.height//call this line after adding the text to the textView
    self.constTextViewHeight.contant = textViewContentHeight
    self.view.layoutIfNeeded()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-20
      • 1970-01-01
      相关资源
      最近更新 更多