为每个实例更改UITableViewCell的宽度约束的常量值

时间:2015-09-07 09:35:45

标签: ios uitableview variables constraints programmatically-created

我正在尝试创建一个聊天应用程序,其中我只使用代码制作了自定义UITableViewCell。所以它就像一个泡泡,泡泡中的名称,消息和时间标签以相同的顺序排列。名称标签应该是总气泡宽度的一半,气泡的宽度由最大宽度为220.0f的信息宽度决定,之后它将转到下一行。

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

我附上一些图片来证明:

更正名称标签的宽度 http://postimg.org/image/yd6z2jdft/c1f192cd/

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

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

的cellForRowAtIndexPath:

public class NewPatient extends Fragment {  
    Button Takeimage, save, cancel;
    int REQUEST_CAMERA = 0, SELECT_FILE = 1;
    ImageView imageview1;
    Uri imageUri;
    private Bitmap bitmap;
    MediaPlayer mp = new MediaPlayer();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View myFragmentView = inflater.inflate(R.layout.activity_new_patient, container, false);


        imageview1 = (ImageView) myFragmentView.findViewById(R.id.imageNP);
        Takeimage = (Button) myFragmentView.findViewById(R.id.takeimg);
        save = (Button) myFragmentView.findViewById(R.id.save);
        cancel = (Button) myFragmentView.findViewById(R.id.cancel);

        Pakage = (Spinner) myFragmentView.findViewById(R.id.packages);
        Takeimage.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
            selectImage();
        }
    });

    imageview1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            getActivity().openOptionsMenu();

        }
    });

    return myFragmentView;
}


private void selectImage() {
    final CharSequence[] items = { "Take Photo", "Choose from Library",
            "Cancel" };

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle("Add Photo!");
    builder.setItems(items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int item) {
            if (items[item].equals("Take Photo")) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, REQUEST_CAMERA);
            } else if (items[item].equals("Choose from Library")) {
                Intent intent = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                intent.setType("image/*");
                startActivityForResult(
                        Intent.createChooser(intent, "Select File"),
                        SELECT_FILE);
            } else if (items[item].equals("Cancel")) {
                dialog.dismiss();
            }
        }
    });
    builder.show();
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == SELECT_FILE)
            onSelectFromGalleryResult(data);
        else if (requestCode == REQUEST_CAMERA)
            onCaptureImageResult(data);
    }
}

private void onCaptureImageResult(Intent data) {
    Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);

    File destination = new File(Environment.getExternalStorageDirectory(),
            System.currentTimeMillis() + ".jpg");

    FileOutputStream fo;
    try {
        destination.createNewFile();
        fo = new FileOutputStream(destination);
        fo.write(bytes.toByteArray());
        fo.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    imageview1.setImageBitmap(thumbnail);
}

@SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
    Uri selectedImageUri = data.getData();
    String[] projection = { MediaColumns.DATA };
    Cursor cursor = getActivity().managedQuery(selectedImageUri, projection, null, null,
            null);
    int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
    cursor.moveToFirst();

    String selectedImagePath = cursor.getString(column_index);

    Bitmap bm;
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(selectedImagePath, options);
    final int REQUIRED_SIZE = 200;
    int scale = 1;
    while (options.outWidth / scale / 2 >= REQUIRED_SIZE
            && options.outHeight / scale / 2 >= REQUIRED_SIZE)
        scale *= 2;
    options.inSampleSize = scale;
    options.inJustDecodeBounds = false;
    bm = BitmapFactory.decodeFile(selectedImagePath, options);

    imageview1.setImageBitmap(bm);
}

Heightforrowatindexpath:

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];

ChatTableViewCell.m

课程扩展中的

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

init方法

@property (nonatomic, strong) NSLayoutConstraint *chatNameLabelWidthConstraint;

另一种设置宽度的方法

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];

1 个答案:

答案 0 :(得分:1)

最后,我用比例宽度解决了它。如果使用约束,它肯定会搞砸,但使用比例宽度以及内容拥抱和内容压缩阻力优先级,应该很容易解决问题:

我就这样做了:

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];
相关问题