0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

UITableViewCellのstyle:value2の列幅を変更する方法

Last updated at Posted at 2019-01-05

はじめに

UITableViewCellstylevalue2を指定すると、1行のセルの左側にtextLabel(右寄せ)、右側にdetailTextLabel(左寄せ)が配置され、この2つの列幅は自動調整されるらしいが、明らかにtextLabelの列幅の方が狭い。
作成中のアプリでtextLabelの文字が小さくなってしまう/文字が途中で切れるため、textLabelの列幅を少し広くしたいと色々調べた結果、UITableViewCelllayoutSubviewsメソッドで変更できることが分かった。
備忘録として以下に概要をまとめる。

環境は以下の通り

  • Xcode : 10.1
  • Swift : 4.2.1
  • iOS : 11.1
  • Simulator : iPhone 8 - 12.1

UITableViewCell.CellStyle.value2

UITableViewCellstylevalue2を指定すると、次のスクショのように、(左側の青字)textLabelと(右側の黒字)detailTextLabelが配置される。Appleの公式資料による説明はこちら
(下のスクショでは、textLabeldetailTextLabelの文字サイズを、どちらもシステムフォントの16ポイントに設定している)

スクリーンショット1

列幅の変更方法

上の例では、左側のtextLabelの列幅を広くする必要性を感じないが、列幅を変更する場合は、UITableViewCelllayoutSubviews()をoverrideして変更する。

textLabelの幅を40pixel広くする例
class UITableViewCellEx: UITableViewCell {
    override func layoutSubviews() {
        super.layoutSubviews()
    
        let plusWidth: CGFloat = 40.0
        
        let textLabelFrame = self.textLabel!.frame
        let textLabelWidth = textLabelFrame.size.width + plusWidth
        let textLabelSize = CGSize(width: textLabelWidth, height: textLabelFrame.size.height)
        self.textLabel!.frame = CGRect(origin: textLabelFrame.origin, size: textLabelSize)

        let detailTextLabelFrame = self.detailTextLabel!.frame
        let detailTextLabelX = detailTextLabelFrame.origin.x + plusWidth
        let detailTextLabelWidth = self.frame.size.width - detailTextLabelX
        let detailTextLabelOrigin = CGPoint(x: detailTextLabelX, y: detailTextLabelFrame.origin.y)
        let detailTextLabelSize = CGSize(width: detailTextLabelWidth, height: detailTextLabelFrame.size.height)
        self.detailTextLabel!.frame = CGRect(origin: detailTextLabelOrigin, size: detailTextLabelSize)
    }
}

上のコードのように、textLabelwidth40を加えた分、detailTextLabelの開始位置xにも40を加えて左にずらしている。またdetailTextLabelwidthから40を引く必要があるが、このwidthは実際にセットした文字列の表示長となっているため、cell自身のwidthから開始位置のxを引くことで、残り幅の全部としている。もしセルの右側にアクセサリを配置している場合は、その幅を考慮する必要がある。

結果、下のスクショのように全体が右に(40pixel)ずれたのが分かる。

スクリーンショット2

**NSSting.size(withAttributes:)**メソッドを使えば、もっときめ細かいサイズ調整ができると思われる。

以上
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?