Текстовая метка ячейки таблицы не содержит всех строк

я хочу сделать динамическую метку высоты в своей пользовательской ячейке UITableView, для этого я пишу код как

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifierTwo=@"CellThree";
    LargeTableViewCell *cellThree=[tableView dequeueReusableCellWithIdentifier:CellIdentifierTwo];
    if (cellThree == nil)
    {
        NSArray *nibTwo=[[NSBundle mainBundle]loadNibNamed:@"LargeTableViewCell" owner:self options:nil];
        cellThree=[nibTwo objectAtIndex:0];
    }
    {
        cellThree.selectionStyle=UITableViewCellSelectionStyleNone;
        NSString *str = [[self.jsonDictionary valueForKey:@"review"]objectAtIndex:0];
        CGRect frame = [str boundingRectWithSize:CGSizeMake(288, CGFLOAT_MAX)
                                          options:NSStringDrawingUsesLineFragmentOrigin
                                       attributes:nil
                                          context:nil];
        cellThree.largeTextView.frame = frame;
        cellThree.contentView.layer.cornerRadius=4.0f;
        if (![self.jsonDictionary isKindOfClass:[NSNull class]])
        {
            cellThree.largeTextView.text=[[self.jsonDictionary valueForKey:@"review"]objectAtIndex:0];
        }
    }
    [cellThree layoutSubviews];
    return cellThree;
  }

и метод tableview heightForRowAtIndexPath вроде как

NSString *str = [[self.jsonDictionary valueForKey:@"review"]objectAtIndex:0];
    CGRect frame = [str boundingRectWithSize:CGSizeMake(288, CGFLOAT_MAX)
                                     options:NSStringDrawingUsesLineFragmentOrigin
                                  attributes:nil
                                     context:nil];
    return frame.size.height+50;

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

<p>The potential of a geographically mobile spirit is vast. When Ravi Babu (playing the spirit) made a surreptitious visit to the police station eavesdropping on Mohinis (Poorna) complaint, comfortably seated next to her, it was clear that the spirit was here to say as its freedom of movement cant be restricted by whatever means. In Avunu-2, it (or, should we say he because the spirit is a rapist?) arrives on the scene using the elevator and enters the new, upscale apartment through the main door.    </p><p>The migration-capable rapist-spirit is also tech-savvy and nothing can stop him except an amulet made in Varanasi. The characters at the receiving end, too, are the same, with an addition made in the form of Harshas friend. After being scared in the old, relatively low-budget flat in Avunu-1, the young couple are all gung-ho about nocturnal as well as day-time romance alike (in one scene, a lip-lock is hindered by an unromantic glass pane), having seemingly forgotten all about their recent near-death experience. So much so, when Mohini says Raju mallee vachadu, Harsha shouts back, saying Clear ga chepu. What? Seriously?    </p><p>In the first part we saw how a newly married couple was prevented by the spirit of Raju from consummating their marriage. He wants to possess the good husband and in his lecherous mission, he was aided by a foolhardy husband who forced his wife to stay in the flat despite she being devastated and extremely frightened. That was Part-I. Here you have a camera-woman who can capture a spirit and presumably even change the world asking Mohini to do the unthinkable.    </p><p>Part-II is a sorry repetition of the first part, but the novelty of the concept is badly over-used to the point of looking jaded. There is the same leering away at a nude Mohini while she is bathing, there is the same pulling off the rug while the couple is sleeping, there are the same attempts to undress her (this time by the good husband, too), there is the same technology-enabled hint that a third entity is roaming about.    </p><p>Whereas in the first part Gods power could not defeat the evil, here it succeeds for good part. The evil spirit may well leave the world exactly after one year, not a single minute delayed. Or, so we think. It strikes back, in another locality, at Prabhas Sreenus curses.    </p><p>Screenplay-wise, this is definitely not in the same league as Ravi Babus other films. While presenting the new element of a drunkard neighbor who with his bizarre tantrums and loving affection towards his wife (he says bangaram to her, at all times) presents a dichotomous picture, Ravi Babu scores on the concept but surely fails on the treatment . One waits for something interesting about his story and the climax doesnt disappoint. The couple is played by Nikita and a well-known character artiste.    </p><p>Just to make sure Sanjjanas incredible camera is established in the audiences mind, Ravi Babu goes for a scene that borders on the stupid, both idea-wise and execution-wise.    </p><p>The hi-tech apartment is a visual treat for sure. The scene where Harshas friend explains the features like a salesman could have been avoided.    </p><p>Ravi Babu banks on some voyeuristic moments here and there. There is no intelligence in story-telling and enlisting a spiritual camera cant be called innovative. If that is his idea of coming up with something akin to what Villa-2 or the recent Pisachi had, then it is disappointing.    </p><p>In a sequel like this, having the characters behave more intelligently makes all the difference. What do Hasha and Mohini do with their hands-on experience of dealing with the spirit?    </p><p>The performances are on the same lines. Poorna looks less glamorous and Harsha is ok.    </p><p>Verdict: Sans intelligent story-telling, Avunu-2 entertains only in bits and pieces. Good RR and cinematography notwithstanding, the film is more of the same. Even at 107 minutes, the film woks only in bits and pieces.    </p><p>Rating: 2.25/5                               </p>

и моя метка содержит значение, например, как

<p>The potential of a geographically mobile spirit is vast. When Ravi Babu (playing the spirit) made a surreptitious visit to the police station eavesdropping on Mohinis (Poorna) complaint, comfortably seated next to her, it was clear that the spirit was here to say as its freedom of movement cant be restricted by whatever means. In Avunu-2, it (or, should we say he because the spirit is a rapist?) arrives on the scene using the elevator and enters the new, upscale apartment through the main door.    </p><p>The migration-capable rapist-spirit is also tech-savvy and nothing can stop him except an amulet made in Varanasi. The characters at the receiving end, too, are the same, with an addition made in the form of Harshas friend. After being scared in the old, relatively low-budget flat in Avunu-1, the young couple are all gung-ho about nocturnal as well as day-time romance alike (in one scene, a lip-lock is hindered by an unromantic glass pane), having seemingly forgotten all about their recent near-death experience. So much so, when Mohini says Raju mallee vachadu, Harsha shouts back, saying Clear ga chepu. What? Seriously?    </p><p>In the first part we saw how a newly married couple was prevented by the spirit of Raju from consummating their marriage. He wants to possess the good husband and in his lecherous mission, he was aided by a foolhardy husband who forced his wife to stay in the flat despite she being devastated and extremely frightened. That was Part-I. Here you have a camera-woman who can capture a spirit and presumably even change the world asking Mohini to do the unthinkable.    </p><p>Part-II is a sorry repetition of the first part, but the novelty of the concept is badly over-used to the point of looking jaded. There is the same leering away at a nude Mohini while she is bathing, there is the same pulling off the rug while the couple is sleeping, there are the same attempts to undress her (this time by the good husband, too), there is the same technology-enabled hint that a third entity is roaming about.    </p><p>Whereas in the first part Gods power could not defeat the evil, here it succeeds for good part. The evil spirit may well leave the world exactly after one year, not a single minute delayed. Or, so we think. It strikes back, in another locality, at Prabhas Sreenus curses.    </p><p>Screenplay-wise, this is definitely not in the same league as Ravi Babus other films. While presenting the

person iOS Developer    schedule 07.04.2015    source источник
comment
Добавьте код результата jsonDictionary   -  person Rajesh Loganathan    schedule 07.04.2015
comment
я редактирую свой вопрос SVMRAJESH   -  person iOS Developer    schedule 07.04.2015
comment
Вы хотите, чтобы динамическая высота для строк зависела от текста или имела возможность получить строку   -  person Rajesh Loganathan    schedule 07.04.2015
comment
@SVMRAJESH да, у меня возникла эта проблема, я успешно извлекаю строку, но не весь текст моей строки в моей метке.   -  person iOS Developer    schedule 07.04.2015
comment
Для этого вы должны установить numberOfLines; свойство этикетки   -  person Ashok Londhe    schedule 07.04.2015
comment
@AshokLondhe, как найти, сколько строк содержит моя строка и как установить метку, потому что она была динамической.   -  person iOS Developer    schedule 07.04.2015
comment
Вы использовали текстовое представление в ячейке? я спрашиваю, потому что есть другой способ найти высоту текстового представления   -  person chirag shah    schedule 07.04.2015
comment
я использовал textview в ячейке   -  person Ashok Londhe    schedule 07.04.2015
comment
@chiragshah нет, я не использую текстовое представление в своей ячейке, это ярлык.   -  person iOS Developer    schedule 07.04.2015
comment
@AshokLondhe, но я не хочу, чтобы текст прокручивался, тогда как я могу установить размер кадра или содержимого прокрутки, пожалуйста, помогите мне.   -  person iOS Developer    schedule 07.04.2015
comment
вам нужно сначала найти общее количество чартеров в одной строке, а затем для этого вы можете рассчитать количество строк, и вы можете динамически возвращать количество строк   -  person Ashok Londhe    schedule 07.04.2015
comment
Скажите, пожалуйста, что именно вы должны сделать   -  person Ashok Londhe    schedule 07.04.2015
comment
В вашем коде четко видно, что вы использовали textview и нет лейбла   -  person chirag shah    schedule 07.04.2015
comment
@chiragshah Хорошо, дайте мне решение, если я использую текстовое представление в своей ячейке, как установить его динамический размер.   -  person iOS Developer    schedule 07.04.2015


Ответы (3)


Попробуйте этот код:

- (CGSize)heightForText:(NSString *)text Width:(float)expectedWidth Font:(UIFont *)font
{
    CGSize size = CGSizeMake(labelWidth, 9999);
   UITextView *text = [[UITextView alloc]init];
    [text setFont:font];
    [text setText:str];
    return [text sizeThatFits:size];

}

и назвал это в heightForRowAtIndex

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

        NSString *txt = [[self.jsonDictionary valueForKey:@"review"]objectAtIndex:indexPath.row];
        return cellheight + [self heightForText:txt Width:cell.largeTextView.frame.size.width Font:(UIFont *)largeTextView.font];
    }
person chirag shah    schedule 07.04.2015

Попробуйте с этим кодом:

+ (CGFloat)heightForText:(NSString *)text labelWidth:(float)labelWidth font:(UIFont *)font
{
    if(!text || labelWidth == 0 || !font)
        return 0.0f;

    NSDictionary *attributes = @{NSFontAttributeName:font};
    CGSize size = CGSizeMake(labelWidth, 9999);

    CGRect rect = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil];
    CGSize textSize = rect.size;

    return textSize.height;
}

Также измените высоту строк с помощью метода -tableview:heightForRowAtindexPath, используя описанный выше метод.

person Pablo A.    schedule 07.04.2015

Попробуйте это решение:

Шаг 1. Рассчитайте высоту метки в зависимости от текста с помощью этого метода.

- (CGFloat)heightForText:(NSString *)text labelWidth:(float)labelWidth font:(UIFont *)font
{
    CGSize size = CGSizeMake(labelWidth, 9999);
    NSDictionary *attributes = @{NSFontAttributeName:font};
    CGRect rect = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil];
    float textHeight = rect.size.height;
    return textHeight;
}

Шаг 2. Установите высоту ячейки таблицы.

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifierTwo=@"CellThree";
    LargeTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifierTwo];

    NSString *txt = [[self.jsonDictionary valueForKey:@"review"]objectAtIndex:indexPath.row];
    return cellheight + [self heightForText:txt labelWidth:cell.largeTextView.frame.size.width font:largeTextView.font];
}
person Rajesh Loganathan    schedule 07.04.2015