2013-12-09 5 views
4

У меня есть пользовательский UITableViewCell, и я пытаюсь изменить размер UITextView внутри него на основе размера контента. Я нахожусь на iOS7 и использую Autolayout.Изменение размера UITextView в пользовательских UITableViewCell

Я попытался с помощью следующих действий:

[cell.question setScrollEnabled:YES]; 
[cell.question sizeToFit]; 
[cell.question setScrollEnabled:NO]; 

и

- (CGRect)textViewHeightForAttributedText: (NSAttributedString*)text andWidth: (CGFloat)width 
{ 
    UITextView *calculationView = [[UITextView alloc] init]; 
    [calculationView setAttributedText:text]; 
    CGSize size = [calculationView sizeThatFits:CGSizeMake(width, FLT_MAX)]; 
    CGRect finalFrame = CGRectMake(0, 0, width, size.height); 
    return finalFrame; 
} 

из различных SO сообщений. Я могу изменить размер рамки. Но проблема в том, что я не вижу видимого изменения. В том смысле, когда я регистрирую его, я вижу изменение. Но UITextView не изменяет размер. Я тоже не могу найти зависимости автозапуска.

Когда я отключил AutoLayout, он работает. Как это сделать, включив AutoLayout?

Спасибо.

EDIT

Вот мои UITextView ограничения

Screenshot

+0

Я думаю, что ответы ниже пригвоздили проблему высоты ячейки, но где ваши ограничения для текстового вида? – bilobatum

+0

Изображение, которое я разместил. Арент те ограничения? – Anil

+0

http://stackoverflow.com/questions/18368567/uitableviewcell-with-uitextview-height-in-ios-7 – wormlxd

ответ

2

Вы должны сделать этот расчет в

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath; 

метод, а также изменить размер высоту ячейки соответственно.

Если у вас есть это, все в порядке. Или, если вам нужен образец кода, просто спросите еще раз. Я думаю, что вы поняли!

Обновлено

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { 
      UITextView *tempTV = [[UITextView alloc] init]; 
      [tempTV setText:@"your text"]; 
      CGFloat width = self.tableView.frame.size.width - TEXT_ORIGIN_X - TEXT_END_X; 
      CGSize size = [tempTV sizeThatFits:CGSizeMake(width, MAX_HEIGHT)]; 
      return (TEXT_ORIGIN_Y + size.height + TEXT_BOTTOM_SPACE); 
    } 
+0

Но я должен уметь видеть, что UITextView изменен правильно? – Anil

+0

Да. Я столкнулся с той же проблемой в прошлом году. И решение заключается в том, что вы должны изменить размер текста в вышеупомянутом методе, а также вернуть вычисленную высоту для строки. –

+0

Как вы справились с этой ситуацией? – Anil

0

Вы можете забыть реализовать метод heightForRowAtIndexPath из delegete Tableview в;

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    CGFloat yourTextViewsHeight = ... calculate it here 
    return yourTextViewsHeight; 
} 
+0

Но я должен уметь видеть, что UITextView изменен правильно? – Anil

+0

Не обязательно. Давайте посмотрим ваши ограничения для текстового представления. Являются ли они в IB? – bilobatum

+0

@bilobatum Пожалуйста, проверьте изменение – Anil

-1

попробовать это

установить розетку UITextView, как это в пользовательских UITableViewCell класс

[yourTextView setAutoresizesSubviews:YES]; 
yourTextView.autoresizingMask = UIViewAutoresizingFlexibleWidth; 

надеюсь, что это будет работать для вас

+0

Это не помогает – Anil

+0

OP использует автозапуск, забывает изменить размер маски. –

0

Я думаю, что вы, возможно, слишком много ограничений для текстовое представление. Я не могу быть уверен в этом, потому что сложно сообщить информацию о ограничениях, которые встроены в IB.

Ваше текстовое представление требует только двух ограничений, по одному для каждой оси, чтобы быть полностью ограниченным. Одно ограничение должно позиционировать текстовое представление горизонтально, другое - вертикально. Размер внутреннего содержимого текстового представления будет использоваться системой автоматического макета для автоматического создания ограничений размера для текстового представления.

Я думаю, что некоторые из ограничений, которые у вас есть сейчас, предотвращают изменение размера текстового вида. Это происходит потому, что по умолчанию требуются ограничения, которые вы создаете сами (приоритет 1000).С другой стороны, автоматически сгенерированные ограничения размеров имеют более низкий приоритет и будут отменены любыми конфликтующими ограничениями, которые требуются.

Примечание: только потому, что текстовое представление требует только двух ограничений, которые должны быть полностью ограничены, не означает, что у вас не может быть больше ограничений. Ячейка таблицы с 4 ярлыками, 3 изображениями и 1 текстовым видом представляет собой сложный макет, поэтому вы, скорее всего, сдерживаете другие объекты пользовательского интерфейса относительно текстового представления, а не супервизора.

0
I had the same issue but in a different situation. I have UItableview with two custom cells. 

First Custom cell - self expanding textview. (like email type message box) 
Second Custom Cell - Static image. 

Have a look at my code. You will get an insight to automatic resizing of cells. 

// ViewController.swift 
// ListWrap 

import UIKit 

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate, UITextViewDelegate { 

    @IBOutlet var listWrapTableView: UITableView! 

    //CustomCells 
    var CellIdentifier: String = "ListWrapTableViewCellID" 
    var tapGesture: UITapGestureRecognizer! 

    override func viewDidLoad() { 
     super.viewDidLoad() 
    } 
    override func viewWillAppear(animated: Bool) { 
     //Adding Tap Gesture To Table 
     tapGesture = UITapGestureRecognizer(target: self, action: "tapRecognized:") 
     self.listWrapTableView.addGestureRecognizer(tapGesture) 
     tapGesture.cancelsTouchesInView = false 
     tapGesture.enabled = true 
    } 
    func tapRecognized(recognizer: UITapGestureRecognizer){ 
     self.listWrapTableView.endEditing(true) 
    } 
    func textViewDidBeginEditing(textView: UITextView) { 
     if (CellIdentifier == "ListWrapTableViewCellID") 
     { 
      tapGesture.enabled = true 
     } 
     else 
     { 
      tapGesture.enabled = false 
     } 
    } 
    // MARK: - Table view data source 
    func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
     return 1 
    } 
    func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat 
    { 
     self.listWrapTableView.rowHeight = UITableViewAutomaticDimension 
     return self.listWrapTableView.rowHeight 
    } 
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { 
     return UITableViewAutomaticDimension 
    } 
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return 2 
    } 
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 

     if (indexPath.row == 0) 
     { 
      let surveyCell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier)! as! ListWrapTableViewCell 
      return surveyCell 
     } 
     else if (indexPath.row == 1) 
     { 
      let reportsCell = tableView.dequeueReusableCellWithIdentifier("ListWrapSecondTableViewCellID")! as! ListWrapSecondTableViewCell 
      return reportsCell 
     } 
     else 
     { 
      let cell:UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "") 
      return cell 
     } 
    } 
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) 
    { 
    } 
} 



The first Custom cell: 

// ListWrapTableViewCell.swift 
// ListWrap 

import UIKit 

class ListWrapTableViewCell: UITableViewCell{ 

    @IBOutlet var listWrapTextView: UITextView! 

// 
// override init?(style: UITableViewCellStyle, reuseIdentifier: String!) { 
//  super.init(style: style, reuseIdentifier: reuseIdentifier) 
// } 

    required init(coder aDecoder: NSCoder) { 
     super.init(coder: aDecoder)! 
    } 

    /// Custom setter so we can initialise the height of the text view 
    var textString: String { 
     get { 
      return listWrapTextView.text 
     } 
     set { 
      listWrapTextView.text = newValue 
      textViewDidChange(listWrapTextView) 
     } 
    } 

    override func awakeFromNib() { 
     super.awakeFromNib() 
     listWrapTextView.scrollEnabled = false 
     listWrapTextView.delegate = self 
    } 
    override func setSelected(selected: Bool, animated: Bool) { 
     super.setSelected(selected, animated: animated) 
     if selected { 
      listWrapTextView.becomeFirstResponder() 
     } else { 
      listWrapTextView.resignFirstResponder() 
     } 
    } 
} 
extension ListWrapTableViewCell: UITextViewDelegate { 
    func textViewDidChange(textView: UITextView) { 

     let size = textView.bounds.size 
     let newSize = textView.sizeThatFits(CGSize(width: size.width, height: CGFloat.max)) 

     // Resize the cell only when cell's size is changed 
     if size.height != newSize.height { 
      UIView.setAnimationsEnabled(false) 
      tableView?.beginUpdates() 
      tableView?.endUpdates() 
      UIView.setAnimationsEnabled(true) 

      if let thisIndexPath = tableView?.indexPathForCell(self) { 
       tableView?.scrollToRowAtIndexPath(thisIndexPath, atScrollPosition: .Bottom, animated: false) 
      } 
     } 
    } 
} 
extension UITableViewCell { 
    /// Search up the view hierarchy of the table view cell to find the containing table view 
    var tableView: UITableView? { 
     get { 
      var table: UIView? = superview 
      while !(table is UITableView) && table != nil { 
       table = table?.superview 
      } 

      return table as? UITableView 
     } 
    } 
} 

The second custom cell: 

// ListWrapSecondTableViewCell.swift 
// ListWrap 


import UIKit 

class ListWrapSecondTableViewCell: UITableViewCell { 

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

} 


attaching storyBoard for further reference. 

enter image description here

0

Ваше расположение является немного более сложным, но это не имеет значения, если все настроено правильно.

Вам не нужно ничего рассчитать (используя sizeThatFits).

Все, что вам нужно сделать, это отключить свойство прокрутки UITextView, а затем textViewDidChange вызвать tableView.beginUpdates() и tableView.endUpdates(). Это не нарушает первого ответчика и плавно изменяет размер таблицы.

Для получения более подробного объяснения ознакомьтесь с post I wrote, который также включает рабочий образец проекта.

Смежные вопросы