【问题标题】:Changing UITextView height on orientation change with AutoLayout使用 AutoLayout 在方向更改时更改 UITextView 高度
【发布时间】:2015-02-22 23:08:33
【问题描述】:

我有一个UIScrollView,里面有一个很大的UITextView。我创建了一个约束来使文本视图宽度为 100%,我现在希望文本视图在方向改变时调整高度,但我找不到如何做到这一点。

这是我现在的代码:

var wordLabel = UITextView()
wordLabel.attributedText = wordText
wordLabel.editable = false
wordLabel.scrollEnabled = false
wordLabel.setTranslatesAutoresizingMaskIntoConstraints(false)

let wordLabelSize = wordLabel.sizeThatFits(maxLabelsSize)
wordLabel.frame = CGRectMake(0, 0, wordLabelSize.width, wordLabelSize.height)
wordLabel.center = CGPoint(x: wordLabel.frame.width / 2, y: wordLabel.frame.height / 2)
scrollView.addSubview(wordLabel)


let wordLabelConstraintWidth = NSLayoutConstraint(item: wordLabel, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: scrollView, attribute: NSLayoutAttribute.Width, multiplier: 1, constant: -32)
scrollView.addConstraint(wordLabelConstraintWidth)

scrollView.contentSize = CGSize(width: scrollView.frame.width - 32, height: wordLabel.frame.origin.y + wordLabel.frame.height)

scrollViewwordLabel 大小在应用启动时是正确的,但是当方向变为横向时,滚动会变得太高。

我真的不知道如何在方向改变时重新计算scrollView contentSize,知道吗?

【问题讨论】:

    标签: ios swift autolayout uitextview


    【解决方案1】:

    你有两种方法:

    1. 设置高度约束,然后执行以下操作:

      wordLabelConstraintHeight.costant = (UIInterfaceOrientationIsLandscape(self.interfaceOrientation)) ? 60.0 : 25.0;
      
    2. 如果textView 应该与屏幕成比例地调整自身大小,您可以使用multiplier

      let wordLabelConstraintHeight = NSLayoutConstraint(item: wordLabel, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: scrollView, attribute: NSLayoutAttribute.Height, multiplier: 0.2, constant: 0)
      

      例如,此代码使您的textView 的高度,您的scrollView 框架的 20%,我确信会根据屏幕尺寸和界面的方向而变化。

    【讨论】:

    • 感谢您的回答。文本视图与滚动视图的高度相同,所以我只需要这样做:let wordLabelConstraintsHeight = NSLayoutConstraint.constraintsWithVisualFormat("V:|[wordLabel]|", options: nil, metrics: nil, views: ["wordLabel": wordLabel]) 想通了!
    • 哦,大声笑..但我认为情况并非如此,显然,如果您只需要将 textView 的边框附加到他的 superview 的边框并具有一个常数值,那么您可以使用视觉格式. ;)
    猜你喜欢
    • 1970-01-01
    • 2013-06-18
    • 1970-01-01
    • 2019-10-12
    • 1970-01-01
    • 2014-04-20
    • 1970-01-01
    • 2015-08-10
    • 1970-01-01
    相关资源
    最近更新 更多