设置文本后,使用自动布局获取UITextView动态高度

时间:2014-11-21 11:16:26

标签: ios objective-c autolayout uitextview

我有一个UITextView不可滚动,界面构建器设置自动布局,文本动态增加或减少没有问题,但我想知道设置文本后新的UITextView高度是多少,我正在尝试这样做:

NSLog(@"text before: %.2f",self.myText.frame.size.height);
[self.myText setText:self.string];
NSLog(@"text after: %.2f",self.myText.frame.size.height);

这是结果:

text before: 47.50
text after: 47.50

运行时文本在视图中增加,但是大小相同,设置文本后如何获得真正的高度?

14 个答案:

答案 0 :(得分:56)

您需要做的就是设置所有约束,但高度为 AND textView scrollEnabled NO设置为update table1 set firstname = (select top 1 firstname from table2 order by NEWID()) 。最后一部分就是诀窍。您的文本视图将根据其文本值自动调整大小。

答案 1 :(得分:18)

如果您希望通过自动布局完成所有操作:

在尺寸检查器中:

  1. 内容压缩阻抗优先级垂直设置为1000.

  2. 降低UITextView的约束高度优先级。只需使它低于1000。

  3. enter image description here

    在属性检查器中:

    1. 取消选中滚动已启用

答案 2 :(得分:13)

这应该有效:

NSLog(@"text before: %.2f",self.myText.frame.size.height);
[self.myText setText:self.string];
[self.myText layoutIfNeeded]; // <--- Add this
NSLog(@"text after: %.2f",self.myText.frame.size.height);

这是我的Github上的示例实现:https://github.com/guillaume-algis/SO-27060338

答案 3 :(得分:12)

我使用了以下链接AutoLayout with Dynamic UITextView height中给出的代码,它对我有用:)

答案 4 :(得分:6)

使用以下代码:

Objective-C代码

textView.isScrollEnabled = false

Swift Code

ImageSaveController

答案 5 :(得分:6)

Swift 3.0

v-bind:href

这允许AutoLayout完成其工作。

答案 6 :(得分:2)

更改文本调用后

[self.myText sizeToFit];

答案 7 :(得分:2)

与UILabel不同,UITextView没有固有的大小属性。所以我如何设置UITextView的高度约束,通过IBOutlet挂钩,并在textViewDidChange或文本更改时更改其值。

@IBOutlet weak var textViewHeight: NSLayoutConstraint!

func textViewDidChange(textView: UITextView) {

    // dynamic height adjustments

    var height = ceil(textView.contentSize.height) // ceil to avoid decimal

    if height != textViewHeight.constant { // set when height changed
        textViewHeight.constant = height
        textView.setContentOffset(CGPointZero, animated: false) // scroll to top to avoid "wrong contentOffset" artefact when line count changes
    }
}

答案 8 :(得分:1)

- (void)textViewDidChange:(UITextView *)textView
{
    UIFont *myFont = [UIFont systemFontOfSize:14];
    CGSize size =   [self sizeOfText:textView.text widthOfTextView:TextviewWidth withFont:myFont];
    NSLog(@"Height : %f", size.height);
}

-(CGSize)sizeOfText:(NSString *)textToMesure widthOfTextView:(CGFloat)width withFont:(UIFont*)font
{
    CGSize ts = [textToMesure sizeWithFont:font constrainedToSize:CGSizeMake(width-20.0, FLT_MAX) lineBreakMode:NSLineBreakByWordWrapping];
    return ts;
}

答案 9 :(得分:1)

选择textview并取消选中“Scrolling enabled”

从顶部菜单选择textview“编辑&gt;尺寸以适合内容”

选择下面的视图,将顶部约束设置为 textview底部到您想要的任何边距,然后转到“尺寸检查器”,双击或编辑您刚添加的约束,并将“关系”设置为“大于或等于”

答案 10 :(得分:1)

另一种方法是使用

myTextView.textContainer.heightTracksTextView = true

允许启用滚动

答案 11 :(得分:0)

嗯,我还没有将此代码转换为swift4语法,但是逻辑将保持不变。这是Xamarin.ios(C#)的扩展方法。

public static nfloat GetEstimateHeight(this UITextView textView, UIView View)
{
    var size = new CoreGraphics.CGSize(View.Frame.Width, height: float.PositiveInfinity);
    var estimatedSize = textView.SizeThatFits(size);
    return estimatedSize.Height;
}

这里适用于迅速的逻辑是

var size = new CoreGraphics.CGSize(View.Frame.Width, height: float.PositiveInfinity);
    var estimatedSize = textView.SizeThatFits(size);
    var textViewFinalHeight = estimatedSize.Height;

答案 12 :(得分:0)

只需按照@Pavel Gurov的回答添加即可。如果您已经设置了高度限制,只需使其不活动即可。之后也值得致电.sizeToFit(),以确保执行了调整大小操作。

theTextViewHeightConstraint.isActive = false

theTextView.isScrollEnabled = false
theTextView.text = "some text"
theTextView.sizeToFit()

答案 13 :(得分:0)

使用纯swift代码设计增加textview高度。我只做编码部分。

这个想法来自 https://stackoverflow.com/a/45071002/9110213

首先创建 textView

    import UIKit
    
    class TextFieldCell: UITableViewCell {
        
        lazy var btnEdit: UIButton! = {
          
          let button = UIButton()
          button.translatesAutoresizingMaskIntoConstraints = false
          button.addTarget(self, action: #selector(self.actionEdit(_:)), for: .touchUpInside)
          button.setTitle("Edit", for: .normal)
          button.titleLabel?.font = UIFont(name: "ProximaNova-Medium", size: 18)
          button.setTitleColor( UIColor(red: 0.29, green: 0.56, blue: 0.89, alpha: 1), for: .normal)
          button.titleLabel?.textAlignment = .left
          return button
          
        }()
      
      lazy var separatorView: UIView! = {
        
        let view = UIView()
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
        
      }()
      
      lazy var textView: UITextView! = {
        
        let textView = UITextView.init(frame: .zero)
        textView.translatesAutoresizingMaskIntoConstraints = false
        textView.delegate = self
        textView.isScrollEnabled = false
        return textView
        
      }()
      
      lazy var titleLabel: UILabel! = {
        
        let label = UILabel(frame: CGRect(x: 27, y: 318, width: 27, height: 12))
        label.text = "Name"
        label.font = UIFont(name: "ProximaNova-Medium", size: 10)
        label.textColor = UIColor(red: 0.61, green: 0.61, blue: 0.61, alpha: 1)
        label.textAlignment = .left
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
        
      }()
        
      
      deinit {
        self.titleLabel = nil
        self.textView = nil
        self.separatorView = nil
        self.btnEdit = nil
      }
        
      override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        self.selectionStyle = .none
        
        self.addView()
        self.setConstraint()
        
      }
      
      required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
      }
      
    }
    
    extension TextFieldCell {
    
      func addView(){
        
        self.contentView.addSubview(self.btnEdit)
        self.contentView.addSubview(self.titleLabel)
        self.contentView.addSubview(self.textView)
        self.contentView.addSubview(self.separatorView)
    
      }
      
      func setConstraint(){
        
       // This part is very important to increase the textview height dyamically   

        let textViewHeight = self.textView.heightAnchor.constraint(equalToConstant: 27)
        textViewHeight.priority = .defaultHigh
        self.textView.setContentCompressionResistancePriority(.required, for: .vertical)
        self.textView.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
    
        NSLayoutConstraint.activate([
          
          self.titleLabel.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor, constant: 27),
          self.titleLabel.topAnchor.constraint(equalTo: self.contentView.topAnchor, constant: 38),
          
          self.textView.topAnchor.constraint(equalTo: self.titleLabel.bottomAnchor, constant: 9),
          self.textView.leadingAnchor.constraint(equalTo: self.titleLabel.leadingAnchor),
          textViewHeight,
          self.textView.trailingAnchor.constraint(equalTo: self.btnEdit.leadingAnchor, constant: -25),
    
          self.btnEdit.centerYAnchor.constraint(equalTo: self.textView.centerYAnchor),
          self.btnEdit.widthAnchor.constraint(equalToConstant: 40),
          self.btnEdit.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor, constant: -33),
          
          self.separatorView.topAnchor.constraint(equalTo: self.textView.bottomAnchor, constant: 10),
          self.separatorView.heightAnchor.constraint(equalToConstant: 1),
          self.separatorView.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor),
          self.separatorView.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor, constant: 27),
          self.separatorView.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor, constant: -15),
          
        ])
        
      }
      
    }
    
    extension TextFieldCell {
    
         @objc func actionEdit(_ sender: UIButton) {
            
        }
      
    }
    
    extension TextFieldCell: UITextViewDelegate {
      func notifyViewController(text:String){
        
      }
      func textViewDidEndEditing(_ textView: UITextView) {
        
      }
    }