为每个实例更改UITableViewCell的宽度约束的常量值 [英] Changing UITableViewCell's width constraint's constant value for each instance

查看:451
本文介绍了为每个实例更改UITableViewCell的宽度约束的常量值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个聊天应用程序,其中我已经使用只有代码的自定义UITableViewCell。所以它就像一个泡沫,名称,消息和时间标签内的泡沫在相同的顺序。名称标签应为气泡总宽度的一半,并且气泡的宽度由消息的最大宽度为220.0f的宽度决定,之后它将转到下一行。



我面临的问题是:我试图根据消息宽度更改名称标签的宽度约束的常量。但是由于iOS重用单元格,当我滚动我的UITableView一些名称标签的宽度搞乱了。它尝试使用旧的宽度,因此,如果名称足够大,名称标签就会消失。



我附加了一些图片来证明: p>

正确的标签宽度
http: //postimg.org/image/yd6z2jdft/c1f192cd/



由于滚动而导致的名称标签宽度错误
http://postimg.org/image/u0m7pc8uh/cd7ea4ea/



这里是我使用的代码。我只发布相关部分



cellforrowatindexpath:

  chatCell = (ChatTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@chatSend]; 

if(chatCell == nil)
{
chatCell = [[ChatTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@chatSend];
}

chatCell.chatMessageLabel.text = message.getMessage;

chatCell.chatNameLabel.text = message.getFromName;

chatCell.chatTimeLabel.text = [dateFormatter stringFromDate:messageDateTime];

[chatCell setChatNameLabelWidth:Messagesize.width];

Heightforrowatindexpath:

  Messagesize = [message.getMessage boundingRectWithSize:CGSizeMake(220.0f,CGFLOAT_MAX)
选项:NSStringDrawingUsesLineFragmentOrigin
属性:@ {NSFontAttributeName:[UIFont boldSystemFontOfSize:14]}
上下文: nil] .size;类扩展程序中的

ChatTableViewCell.m



  @property(nonatomic,strong)NSLayoutConstraint * chatNameLabelWidthConstraint; 

init方法

 code> horizo​​ntal = [NSLayoutConstraint constraintsWithVisualFormat:@H:| -16- [chatNameLabel]options:NSLayoutFormatDirectionLeftToRight metrics:nil views:NSDictionaryOfVariableBindings(chatNameLabel) 


[Main addConstraints:horizo​​ntal];

// ////////////////////////////////////////// ////////////////////////////////////////////////// //

//为chatNameLabel设置宽度约束

chatNameLabelWidthConstraint = [NSLayoutConstraint constraintWithItem:chatNameLabel attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.f constant :64.0f];

[chatNameLabel addConstraint:chatNameLabelWidthConstraint];

// ////////////////////////////////////////// //////////////////////////////////////////////////// //


//设置chatNameLabel的约束。它应该在距离superview的右边和左边16距离,即Main和距离顶部的距离为8,并且chatMessageLabel距离chatTimeLabel的距离为8,距离superview的底部8个距离。



vertical = [NSLayoutConstraint constraintsWithVisualFormat:@V:| -8- [chatNameLabel] -8- [chatMessageLabel] -8- [chatTimeLabel] -8- | options:0 metrics:nil views:NSDictionaryOfVariableBindings(chatNameLabel,chatMessageLabel,chatTimeLabel)];

[Main addConstraints:vertical];

另一种设置宽度的方法

   - (void)setChatNameLabelWidth:(CGFloat)messageWidth 
{
CGFloat chatNameLabelWidth;

if((messageWidth + 32.0f)< 128.0f)
{
chatNameLabelWidth = 64.0f;
}
else
{
chatNameLabelWidth =(messageWidth + 32.0f)/ 2;
}

chatNameLabelWidthConstraint.constant = chatNameLabelWidth;

[chatNameLabel layoutIfNeeded];
}


解决方案

比例宽度。如果使用了约束,它肯定会弄乱,但使用成比例的宽度以及内容拥抱和内容压缩抗性优先级,应该很容易解决这个问题:



这是我如何是否:

  NSLayoutConstraint * proportionalWidth = [NSLayoutConstraint constraintWithItem:chatNameLabel 
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:Main
attribute:NSLayoutAttributeWidth
multiplier:.5
constant:0];

proportionalWidth.priority = 750;


[Main addConstraint:proportionalWidth];

[chatNameLabel setContentCompressionResistancePriority:250 forAxis:UILayoutConstraintAxisHorizo​​ntal];


I am trying to create a chat application where in I have made a custom UITableViewCell using only code. So it is like a bubble with Name, message and time labels inside the bubble in the same order. The name label should be half of the total bubble's width and the bubble's width is determined by the width of the message whose maximum width is 220.0f after which it will go to next line.

The problem that I am facing is: I am trying to change the name label's width constraint's constant according to the message width. But since iOS reuses the cell, when I scroll my UITableView some of the name label's width gets messed up. It tries to use the old width and therefore, the name label gets out of the bubble if name is big enough.

I am attaching some images to demonstrate that:

Correct width of Name Label http://postimg.org/image/yd6z2jdft/c1f192cd/

Wrong width of Name label because of scroll http://postimg.org/image/u0m7pc8uh/cd7ea4ea/

Here is the code I am using. I am posting only the relevant part

cellforrowatindexpath:

chatCell = (ChatTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"chatSend"];

        if (chatCell == nil)
        {
            chatCell = [[ChatTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"chatSend"];
        }

        chatCell.chatMessageLabel.text = message.getMessage;

        chatCell.chatNameLabel.text = message.getFromName;

chatCell.chatTimeLabel.text = [dateFormatter stringFromDate:messageDateTime];

[chatCell setChatNameLabelWidth:Messagesize.width];

Heightforrowatindexpath:

Messagesize = [message.getMessage boundingRectWithSize:CGSizeMake(220.0f, CGFLOAT_MAX)
                                                   options:NSStringDrawingUsesLineFragmentOrigin
                                                attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:14]}
                                                   context:nil].size;

ChatTableViewCell.m

in class extension

@property (nonatomic, strong) NSLayoutConstraint *chatNameLabelWidthConstraint;

init method

horizontal = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-16-[chatNameLabel]" options:NSLayoutFormatDirectionLeftToRight metrics:nil views:NSDictionaryOfVariableBindings(chatNameLabel)];


    [Main addConstraints:horizontal];

    // ////////////////////////////////////////////////////////////////////////////////////////////

    //Setting width constraint for chatNameLabel

    chatNameLabelWidthConstraint = [NSLayoutConstraint constraintWithItem:chatNameLabel attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.f constant:64.0f];

    [chatNameLabel addConstraint:chatNameLabelWidthConstraint];

    // ////////////////////////////////////////////////////////////////////////////////////////////


    //Setting the constraints for chatNameLabel. It should be at 16 distance from right and left of superview, i.e., Main and 8 distance from top and chatMessageLabel which is at 8 distance from chatTimeLabel which is at 8 distance from bottom of superview.



    vertical = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-8-[chatNameLabel]-8-[chatMessageLabel]-8-[chatTimeLabel]-8-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(chatNameLabel,chatMessageLabel,chatTimeLabel)];

    [Main addConstraints:vertical];

Another method to set width

- (void)setChatNameLabelWidth:(CGFloat) messageWidth
{
    CGFloat chatNameLabelWidth;

    if((messageWidth + 32.0f)<128.0f)
    {
        chatNameLabelWidth = 64.0f;
    }
    else
    {
        chatNameLabelWidth = (messageWidth + 32.0f)/2;
    }

    chatNameLabelWidthConstraint.constant = chatNameLabelWidth;

    [chatNameLabel layoutIfNeeded];
}

解决方案

Finally, I solved it using proportional width. If constraint is used, it will surely get messed up but using proportional width along with content hugging and content compression resistance priorities, should solve the problem easily:

This is how I did it:

NSLayoutConstraint *proportionalWidth = [NSLayoutConstraint constraintWithItem:chatNameLabel
                                                         attribute:NSLayoutAttributeWidth
                                                         relatedBy:NSLayoutRelationEqual
                                                            toItem:Main
                                                         attribute:NSLayoutAttributeWidth
                                                        multiplier:.5
                                                          constant:0];

    proportionalWidth.priority = 750;


    [Main addConstraint:proportionalWidth];

    [chatNameLabel setContentCompressionResistancePriority:250 forAxis:UILayoutConstraintAxisHorizontal];

这篇关于为每个实例更改UITableViewCell的宽度约束的常量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆