如何在UITableview中对齐标签



我有一个UITableView,其中有不同大小的图像。所以当我运行程序时,我在TableView中得到了不同的标签起点。

我希望所有标签都从同一点开始。

对齐对我不起作用。我希望所有标签都从左起一定距离。

有什么解决办法吗?

从UITableViewCell派生一个类。

重写方法layoutSubviews。在这种方法中,为所有组件设置合适的帧,如图像视图、主标签等。

CustomCell.h

@interface CustomCell : UITableViewCell
{
}
@end

CustomCell.m

@implementation CustomCell
    -(void) layoutSubviews
    {
         [super layoutSubviews];
        self.imageView.frame = SOME_FRAME;
        self.textLabel.frame = SOME_OTHER_FRAME;
    }
@end

现在,不要在cellForRowAtIndexPath中从UITableViewCell创建单元格,而是使用上面的单元格。

您的标签位置是否因为图像而受到干扰?

如果是,那么有两种方法1

[imgView setContentMode:UIViewContentModeScaleToFill]

2您应该首先获得图像视图的宽度,然后添加一些空间因子,然后为您的uilabel设置适当的起点。

UILabel *lbl = ...;
UIImageView * imgView = ....;
CGRect lblFrame = lbl.frame;
lblFrame.origin.x = imgView.frame.origin.x + imgView.frame.size.width + 10;
[lbl setFrame:lblFrame];

编辑:

如果调整uiimage的大小不是问题,那么调整图像的大小。。。

+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
    //UIGraphicsBeginImageContext(newSize);
    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();    
    UIGraphicsEndImageContext();
    return newImage; }

区块报价

> [CLASSNAME imageWithImage:yourImage scaledToSize:CGSizeMake(50,50)];

试试这段代码,在UiTableView中对齐UILabel非常有用:UILabel*label=[[UILabel alloc]init];

    label.frame=CGRectMake(80, 2, 180, 60);
    label.backgroundColor=[UIColor clearColor];
    label.text=[ShopListOfItems objectAtIndex:indexPath.row];
    label.textColor=[UIColor whiteColor];
    label.font=[UIFont boldSystemFontOfSize:20];
    label.numberOfLines=2;
    [cell.contentView addSubview:label];

最新更新