2015-06-25 5 views
1

В настоящее время я создаю приложение для социальных сетей, которое отображает записи пользователя в таблице. Каждое сообщение будет отображаться в одной ячейке таблицы. Поскольку я не знаю, сколько пользователь будет печатать для одного сообщения, мне нужно установить размер текстового вида в соответствии с количеством текста, набранного пользователем. Проблема в том, что моя текущая реализация не работает и ведет себя странно.Изменить размер UITextView в соответствии с текстом в UITableViewCell

Вот мой стол код:

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { 

    let cell : UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("HomeCell") as? UITableViewCell 
    let post : Post = tblData[indexPath.row] 

    //Get all custom cell components 
    let userLbl = cell?.viewWithTag(101) as UILabel 
    let timeLbl = cell?.viewWithTag(102) as UILabel 
    let postLbl = cell?.viewWithTag(103) as UITextView 
    let profilePic = cell?.viewWithTag(100) as UIImageView 
    let postPic = cell?.viewWithTag(104) as UIImageView 

    //Post lbl properties 
    let textHeight = textViewDidChange(postLbl) 
    postLbl.frame.size.height = CGFloat(textHeight) 
    //postLbl.selectable = false 

    //Individual height variables 
    let postInfoHeight = 66 as CGFloat 
    var postHeight = 8 + CGFloat(textHeight) 
    var imgHeight = 8 + postPic.frame.height as CGFloat 

    if post.postInformation == "" { 
     postLbl.removeFromSuperview() 
     postHeight = 0 
    } 

    if post.img == nil { 
     postPic.removeFromSuperview() 
     imgHeight = 0 
    } 

    //Change the autolayout constraints so it works properly 
    return postInfoHeight + postHeight + imgHeight 
} 

и вот код, который вычисляет высоту текстовой:

func textViewDidChange(textView : UITextView) -> Float { 

    let content : NSString = textView.text 
    let oneLineSize = content.sizeWithAttributes(["NSFontSizeAttribute": UIFont.systemFontOfSize(14.0)]) 

    let contentSize = CGSizeMake(textView.frame.width, oneLineSize.height * round(oneLineSize.width/textView.frame.width)) 

    return Float(contentSize.height) 
} 

Я не могу понять, почему это не дает мне правильные результаты. Если кто-нибудь может обнаружить ошибку или предложить, как решить эту проблему, я бы очень признателен. Заранее спасибо!

+0

Какие результаты это дает вам? Слишком высокий или слишком короткий? Вырезание линий? – jrisberg

+0

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

+0

Вы проверили, что 'postLbl' не является нулевым и содержит в нем текст? – jrisberg

ответ

0

Спасибо @jrisberg за ссылку на другой вопрос. Я решил отказаться от использования текстового вида, и теперь я использую UILabel. Код в другом вопросе чрезвычайно старый и использует много устаревших методов, поэтому я опубликую обновленный код, который работает на iOS 8 здесь. Я удалил метод textViewDidChange(textView : UITextView) и изменил мой tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) метод это:

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { 

    let cell : UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("HomeCell") as? UITableViewCell 
    let post : Post = tblData[indexPath.row] 

    //Get custom cell components 
    let postLbl = cell?.viewWithTag(103) as UILabel 
    let postPic = cell?.viewWithTag(104) as UIImageView 

    //Post lbl properties 
    let PADDING : Float = 8 
    let pString = post.postInformation as NSString? 

    let textRect = pString?.boundingRectWithSize(CGSizeMake(CGFloat(self.tableView.frame.size.width - CGFloat(PADDING * 3.0)), CGFloat(1000)), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName : UIFont.systemFontOfSize(14.0)], context: nil) 

    //Individual height variables 
    let postInfoHeight = 66 as CGFloat 
    var postHeight = textRect?.size.height 
    postHeight? += CGFloat(PADDING * 3) 
    var imgHeight = 8 + postPic.frame.height as CGFloat 

    if post.img == nil { 
     postPic.removeFromSuperview() 
     imgHeight = 0 
    } 

    //Change the autolayout constraints so it works properly 
    return postInfoHeight + postHeight! + imgHeight 
} 
Смежные вопросы