Auto Layoutを使用して、Windowいっぱいに広げたUIScrollViewに自動改行するUILabelをいれてもうまく改行されませんでした。解決方法は簡単で、Labelのレイアウト指定の仕方をScrollViewのTop,Left,Right,Bottomから、Top,Left,Width,Bottomに変えればいいだけでした。
import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() //スクロールViewを画面いっぱいに表示 let scrollView = UIScrollView() scrollView.setTranslatesAutoresizingMaskIntoConstraints(false) self.view.addSubview(scrollView) self.view.addConstraints([ NSLayoutConstraint(item: scrollView, attribute: .Top, relatedBy: .Equal, toItem: self.topLayoutGuide, attribute: .Top, multiplier: 1.0, constant: 0), NSLayoutConstraint(item: scrollView, attribute: .Left, relatedBy: .Equal, toItem: self.view, attribute: .Left, multiplier: 1.0, constant: 0), NSLayoutConstraint(item: scrollView, attribute: .Right, relatedBy: .Equal, toItem: self.view, attribute: .Right, multiplier: 1.0, constant: 0), NSLayoutConstraint(item: scrollView, attribute: .Bottom, relatedBy: .Equal, toItem: self.view, attribute: .Bottom, multiplier: 1.0, constant: 0), ]) //ラベルをスクロールViewに追加 var label = UILabel() label.text = "秋の田の かりほの庵の 苫をあらみ 我が衣手は 露にぬれつつ" label.font = UIFont.systemFontOfSize(78) label.numberOfLines = 0; //自動改行用設定 label.lineBreakMode = NSLineBreakMode.ByWordWrapping //自動改行用設定 label.setTranslatesAutoresizingMaskIntoConstraints(false) scrollView.addSubview(label) scrollView.addConstraints([ NSLayoutConstraint(item: label, attribute: .Top, relatedBy: .Equal, toItem: scrollView, attribute: .Top, multiplier: 1.0, constant: 0), NSLayoutConstraint(item: label, attribute: .Left, relatedBy: .Equal, toItem: scrollView, attribute: .Left, multiplier: 1.0, constant: 0), //NSLayoutConstraint(item: label, attribute: .Right, relatedBy: .Equal, toItem: scrollView, attribute: .Right, multiplier: 1.0, constant: 0), NSLayoutConstraint(item: label, attribute: .Width, relatedBy: .Equal, toItem: scrollView, attribute: .Width, multiplier: 1.0, constant: 0), NSLayoutConstraint(item: label, attribute: .Bottom, relatedBy: .Equal, toItem: scrollView, attribute: .Bottom, multiplier: 1.0, constant: 0), ]) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
同じことをswift-layoutで書いた場合
//スクロールViewを画面いっぱいに表示 let scrollView = UIScrollView() Layout.regist(scrollView, superview:self.view) .top(0).fromBottom(self.topLayoutGuide) .leftIsSameSuperview() .widthIsSameSuperview() .bottomIsSameSuperview() //ラベルをスクロールViewに追加 var label = Layout.createWordWrappingLabel("秋の田の かりほの庵の 苫をあらみ 我が衣手は 露にぬれつつ") Layout.regist(label, superview:scrollView) .topIsSameSuperview() .leftIsSameSuperview() .widthIsSameSuperview() .bottomIsSameSuperview() .font(UIFont.systemFontOfSize(78))