前提・実現したいこと
お世話になっております。
調べてもわからなかったので質問させていただきます。
4つ並べたSubViewの中にLabelを表示させております。
このように表示は問題なく行えておりますが、センタリングにズレが生じております。
このズレを修正して、どの端末で利用した際も中央に配置されるように変更したいです。
解決案が分かる方がいらっしゃいましたら、回答いただけましたら幸いです。
何卒宜しくお願いします。
該当のソースコード
let myPageView = UIView() myPageView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width/4, height: 50) myPageView.backgroundColor = .white self.view.addSubview(myPageView) myPageView.translatesAutoresizingMaskIntoConstraints = false myPageView.leadingAnchor.constraint( equalTo: self.view.leadingAnchor, constant: 0 ).isActive = true myPageView.centerYAnchor.constraint( equalTo: self.view.topAnchor, constant: 230 ).isActive = true myPageView.widthAnchor.constraint( equalTo: self.view.widthAnchor, multiplier: 0.25 ).isActive = true myPageView.heightAnchor.constraint( equalToConstant: 50.0 ).isActive = true let rightBorder = CALayer() //topBorder.frame = CGRect(x: 0, y: 0, width: myPageView.frame.width, height: 1.0) rightBorder.frame = CGRect(x: myPageView.frame.width, y: 0, width: 1.0, height:myPageView.frame.height) rightBorder.backgroundColor = UIColor.lightGray.cgColor myPageView.layer.addSublayer(rightBorder) //SubViewにlabel要素追加 let postLabel = UILabel() postLabel.text = "投稿" postLabel.frame = CGRect(x: 0, y:0, width:100, height:21) postLabel.textAlignment = .center postLabel.textColor = UIColor.lightGray postLabel.font = UIFont.boldSystemFont(ofSize: 12) myPageView.addSubview(postLabel) let postLabelNum = UILabel() postLabelNum.text = "1234" postLabelNum.frame = CGRect(x: 0, y:20, width:100, height:21) postLabelNum.textAlignment = .center postLabelNum.textColor = UIColor.lightGray postLabelNum.font = UIFont.boldSystemFont(ofSize: 12) myPageView.addSubview(postLabelNum)
試したこと
センタリングにズレが生じている問題は、Labelの幅がsubViewに対して100%の幅以上になっていることが原因で発生しております。
上記の投稿Viewのように上限以上にwidth幅があるため、postLabelNum.textAlignment = .centerを行なった際に中央の地点がズレます。
これに対してwidth幅を個別の端末のpxに合わせてしまっては端末ごとにやはり中央地点がズレてしまうためwidth幅を指定することでは解決に至りませんでした。
そこで投稿部分のViewareaの幅を100%として取得してくれる書き方を探しましたが、見つかりませんでした。
似たようなコードとしてself.view.bounds.widthを試しましたが、おそらく挙動的にsubViewの幅を認識しているのではなく、ルートビューのサイズに自動調整されてしまいました。
補足情報(FW/ツールのバージョンなど)
xcode9.2
回答に対する補足
let postLabel = UILabel() postLabel.text = "投稿" postLabel.frame = CGRect(x: 0, y:0, width:100, height:21) postLabel.textAlignment = .center postLabel.textColor = UIColor.lightGray postLabel.font = UIFont.boldSystemFont(ofSize: 12) myPageView.addSubview(postLabel) postLabel.translatesAutoresizingMaskIntoConstraints = false postLabel.widthAnchor.constraint( equalTo: self.view.widthAnchor, multiplier: 0.25 ).isActive = true
上記のように2つのUILabelに対してautoLayoutも試しましたが、下記のように空白になってしまいます。
おそらく記載方法の誤りがあると思うのですが、原因がわかりましたらご教授いただけましたら幸いです。
回答2件
あなたの回答
tips
プレビュー