TL;DR
UITableViewAutomaticDimension
上部と下部の両方の制約を使用および設定しているにもかかわらず、プログラムで作成したテーブル ビュー セルが、カスタム ビューの本質的なコンテンツの高さに応じてサイズ変更されません。
問題はおそらく、UITableViewCell
サブクラスの実装にあります。以下のコードを参照してください。プログラムで動作しない > コード > MyCustomCell.swift .
ゴール
カスタムのモンゴル語キーボードの提案バーを作成しようとしています。モンゴル語は縦書きです。Android では、次のようになります。
進捗
UITableView
iOS 8 以降で利用可能な可変セルの高さで を使用する必要があることを学びました。これには、自動レイアウトを使用し、セルの高さに自動寸法を使用するようにテーブル ビューに指示する必要があります。
途中で学ばなければならなかったいくつかのことは、最近の SO の質問と回答に示されています。
- カスタム テーブル ビュー セルの作成方法
- 標準のテーブル ビューで可変高さを取得する
UILabel
- カスタム ビューで機能する固有のコンテンツ サイズを取得する
- プログラムで作成された
UITableViewCell
- プログラムで制約を設定する
そのため、固有のコンテンツ サイズをサポートする垂直ラベルを使用できるようになりました。これらのラベルは、カスタム テーブル ビューのセルに入れられます。また、次のセクションで説明するように、ストーリーボードで実行すると機能しますが、プログラムですべてを作成すると機能しません。
IBで働く
問題を切り分けるために、2 つの基本的なプロジェクトを作成しました。1 つはストーリーボードを使用するプロジェクトで、もう 1 つはプログラムですべてを実行するプロジェクトです。ストーリーボード プロジェクトが機能します。次の図に示すように、各テーブル ビュー セルは、カスタム垂直ラベルの高さに合わせてサイズ変更されます。
IBで
上部と下部を固定し、ラベルを中央に配置するように制約を設定しました。
コード
ViewController.swift
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let myStrings: [String] = ["a", "bbbbbbb", "cccc", "dddddddddd", "ee"]
let cellReuseIdentifier = "cell"
@IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.estimatedRowHeight = 44.0
tableView.rowHeight = UITableViewAutomaticDimension
}
// number of rows in table view
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.myStrings.count
}
// create a cell for each table view row
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:MyCustomCell = self.tableView.dequeueReusableCellWithIdentifier(cellReuseIdentifier) as! MyCustomCell
cell.myCellLabel.text = self.myStrings[indexPath.row]
return cell
}
// method to run when table view cell is tapped
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("You tapped cell number \(indexPath.row).")
}
}
MyCustomCell.swift
import UIKit
class MyCustomCell: UITableViewCell {
@IBOutlet weak var myCellLabel: UIMongolSingleLineLabel!
}
プログラム的に動作しません
提案バーを最終的なキーボードの一部にしたいので、プログラムで作成できる必要があります。ただし、上記のサンプル プロジェクトをプログラムで再作成しようとすると、機能しません。次の結果が得られます。
セルの高さのサイズが変更されておらず、カスタムの垂直ラベルが互いに重なっています。
次のエラーも表示されます。
警告は 1 回のみ: テーブルビュー セルのコンテンツ ビューの高さがゼロであることを制約が曖昧に示唆しているケースが検出されました。意図しない崩壊を考慮し、代わりに標準の高さを使用しています。
このエラーは、スタック オーバーフローで何度も発生しています。
- iOS8 - 制約があいまいにゼロの高さを示唆している
- 制約があいまいにゼロの高さを示唆しているケースを検出しました
- カスタム UITableviewcell の高さが正しく設定されていません
- iOS 8 (UITableViewCell) : 制約は、テーブルビュー セルのコンテンツ ビューの高さゼロをあいまいに提案します
しかし、これらの人々のほとんどの問題は、上下両方のピン制約を設定していないことです。以下の私のコードに示されているように、私はそうです、または少なくとも私はそうだと思います。
コード
ViewController.swift
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let myStrings: [String] = ["a", "bbbbbbb", "cccc", "dddddddddd", "ee"]
let cellReuseIdentifier = "cell"
var tableView = UITableView()
override func viewDidLoad() {
super.viewDidLoad()
// Suggestion bar
tableView.frame = CGRect(x: 0, y: 20, width: view.bounds.width, height: view.bounds.height)
tableView.registerClass(MyCustomCell.self, forCellReuseIdentifier: cellReuseIdentifier)
tableView.delegate = self
tableView.dataSource = self
tableView.estimatedRowHeight = 44.0
tableView.rowHeight = UITableViewAutomaticDimension
view.addSubview(tableView)
}
// number of rows in table view
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.myStrings.count
}
// create a cell for each table view row
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:MyCustomCell = self.tableView.dequeueReusableCellWithIdentifier(cellReuseIdentifier) as! MyCustomCell
cell.myCellLabel.text = self.myStrings[indexPath.row]
return cell
}
// method to run when table view cell is tapped
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("You tapped cell number \(indexPath.row).")
}
}
MyCustomCell.swift
これがIBプロジェクトとの主な違いであるため、問題はおそらくここにあると思います。
import UIKit
class MyCustomCell: UITableViewCell {
var myCellLabel = UIMongolSingleLineLabel()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setup() {
self.myCellLabel.translatesAutoresizingMaskIntoConstraints = false
self.myCellLabel.centerText = false
self.myCellLabel.backgroundColor = UIColor.yellowColor()
self.addSubview(myCellLabel)
// Constraints
// pin top
NSLayoutConstraint(item: myCellLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.contentView, attribute: NSLayoutAttribute.TopMargin, multiplier: 1.0, constant: 0).active = true
// pin bottom
NSLayoutConstraint(item: myCellLabel, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self.contentView, attribute: NSLayoutAttribute.BottomMargin, multiplier: 1.0, constant: 0).active = true
// center horizontal
NSLayoutConstraint(item: myCellLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self.contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0).active = true
}
override internal class func requiresConstraintBasedLayout() -> Bool {
return true
}
}
補足コード
上記の両方のプロジェクトで使用したカスタム垂直ラベルのコードも含めますが、IB プロジェクトは機能するため、主な問題はここにはないと思います。
import UIKit
@IBDesignable
class UIMongolSingleLineLabel: UIView {
private let textLayer = LabelTextLayer()
var useMirroredFont = false
// MARK: Primary input value
@IBInspectable var text: String = "A" {
didSet {
textLayer.displayString = text
updateTextLayerFrame()
}
}
@IBInspectable var fontSize: CGFloat = 17 {
didSet {
updateTextLayerFrame()
}
}
@IBInspectable var centerText: Bool = true {
didSet {
updateTextLayerFrame()
}
}
// MARK: - Initialization
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
func setup() {
// Text layer
textLayer.backgroundColor = UIColor.yellowColor().CGColor
textLayer.useMirroredFont = useMirroredFont
textLayer.contentsScale = UIScreen.mainScreen().scale
layer.addSublayer(textLayer)
}
override func intrinsicContentSize() -> CGSize {
return textLayer.frame.size
}
func updateTextLayerFrame() {
let myAttribute = [ NSFontAttributeName: UIFont.systemFontOfSize(fontSize) ]
let attrString = NSMutableAttributedString(string: textLayer.displayString, attributes: myAttribute )
let size = dimensionsForAttributedString(attrString)
// This is the frame for the soon-to-be rotated layer
var x: CGFloat = 0
var y: CGFloat = 0
if layer.bounds.width > size.height {
x = (layer.bounds.width - size.height) / 2
}
if centerText {
y = (layer.bounds.height - size.width) / 2
}
textLayer.frame = CGRect(x: x, y: y, width: size.height, height: size.width)
textLayer.string = attrString
invalidateIntrinsicContentSize()
}
func dimensionsForAttributedString(attrString: NSAttributedString) -> CGSize {
var ascent: CGFloat = 0
var descent: CGFloat = 0
var width: CGFloat = 0
let line: CTLineRef = CTLineCreateWithAttributedString(attrString)
width = CGFloat(CTLineGetTypographicBounds(line, &ascent, &descent, nil))
// make width an even integer for better graphics rendering
width = ceil(width)
if Int(width)%2 == 1 {
width += 1.0
}
return CGSize(width: width, height: ceil(ascent+descent))
}
}
// MARK: - Key Text Layer Class
class LabelTextLayer: CATextLayer {
// set this to false if not using a mirrored font
var useMirroredFont = true
var displayString = ""
override func drawInContext(ctx: CGContext) {
// A frame is passed in, in which the frame size is already rotated at the center but the content is not.
CGContextSaveGState(ctx)
if useMirroredFont {
CGContextRotateCTM(ctx, CGFloat(M_PI_2))
CGContextScaleCTM(ctx, 1.0, -1.0)
} else {
CGContextRotateCTM(ctx, CGFloat(M_PI_2))
CGContextTranslateCTM(ctx, 0, -self.bounds.width)
}
super.drawInContext(ctx)
CGContextRestoreGState(ctx)
}
}
アップデート
プロジェクトのコード全体はすべてここにあるので、試してみたいという人がいる場合は、新しいプロジェクトを作成し、上記のコードを次の 3 つのファイルにカット アンド ペーストしてください。
- ViewController.swift
- MyCustomCell.swift
- UIMongolSingleLineLabel.swift