2017-01-27 8 views
0

todoのタイトルが含まれているuilabelのフレームを更新しようとしています。そのため、todoの説明がないときに垂直に中央揃えされます。ここUITableViewCell内のUILabelフレームを更新する

cellForRowAt indexPath

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell : customCell = tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as! customCell 

    // Configure the cell... 

    let todo = todos[indexPath.row] 

    cell.setup(todo: todo.title, todoDescription : todo.todoDescription) 

    return cell 
} 

カスタムセルクラスである:

import UIKit 

class customCell: UITableViewCell { 

let titleLabel: UILabel! = UILabel(...) //cenvenience initializer setting the uilabel frame 
let descriptionLabel: UILabel! = UILabel(...) 

func setup(todo : String, todoDescription : String?) { 

    titleLabel.text = todo 

    if let todo_descr = todoDescription { 
     descriptionLabel.text = todo_descr 
    } else { 
     descriptionLabel.text = "" 
     titleLabel.frame = ... //update the frame of the todo title to be centered vertically in the cell, basically change the y of the frame 
    } 

} 

override func layoutSubviews() { 
    super.layoutSubviews() 
    titleLabel.frame = ... //initial frame, which is not centered vertically 
    descriptionLabel.frame = ... 

    contentView.addSubview(titleLabel) 
    contentView.addSubview(descriptionLabel) 
} 

override func awakeFromNib() { 
    super.awakeFromNib() 
    // Initialization code 
} 

override func setSelected(_ selected: Bool, animated: Bool) { 
    super.setSelected(selected, animated: animated) 

    // Configure the view for the selected state 
} 

}

IはtitleLabelフレームを印刷するとき、それは所望のフレームのプロパティを印刷します。しかし、シミュレータでは、フレームはまだラベルに与えられたフレームであるlayoutSubviewsです。

setup機能でself.layoutIfNeeded()を試しましたが、機能しません。どのようにして、セルフサブビューを更新することができますか? cellForRowAtIndexPathで

答えて

0

あなたはtitleLabelの垂直センター、およびすべての作品の枠を設定し、この方法では

cell.setup(todo: todo.title, todoDescription : todo.todoDescription) 

を呼び出します。 しかし、そのセルの後にメソッドlayoutSubviews()が呼び出され、このメソッドでは、説明テキストに依存せずに、ラベルのフレームの初期値を設定します。

titleLabel.frame = ... //initial frame, which is not centered vertically 
descriptionLabel.frame = ... 

すべてのラベル、初期フレームのセット。 問題は、layoutSubviews()メソッドがsetup()メソッドの後に呼び出しを行うことです。 layoutSubviewsメソッドでラベルのフレームを設定する必要はありません。彼らはすでにlabel initializerまたはsetup()メソッドで右フレームの設定をしています。

0

この方法では、藤堂タイトルで、0に藤堂の説明のためのラインの静的な高さ

  • セット数になりますAuto Layout Constraints

    UItableViewCell Design

    1. と以下のようにあなたのUITableViewCellを設計、少ない非常にコードですプロパティ。したがって、説明がない場合、Todoの説明は自動的にその高さをゼロに減らします。私たちは高さ算出方法でUITableViewAutomaticDimension

    を追加し、ビューコントローラ

    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{ 
        return UITableViewAutomaticDimension; 
    } 
    
    
    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{ 
        return UITableViewAutomaticDimension; 
    } 
    
    におけるこれら二つのデータソースメソッドを追加しているので、
  • 関連する問題