在UITableView中画竖线

本文介绍了如何通过自定义UITableViewCell子类MyTableCell,在UITableView中绘制竖线。代码中创建了一个可容纳多列位置的数组,并在`drawRect:`方法内遍历数组,使用Core Graphics绘制竖线。设置线条颜色为黑色,宽度为0.5。在`tableView:cellForRowAtIndexPath:`中使用MyTableCell实例替代默认单元格。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

自定义类,从UITableViewCell继承,头文件如下:

 

#import <UIKit/UIKit.h>

 

 

@interface MyTableCell : UITableViewCell {

 

NSMutableArray *columns;

}

 

- (void)addColumn:(CGFloat)position;

 

@end

 

 

 

实现文件如下:

 

 

 

#import "MyTableCell.h"

@implementation MyTableCell

 

- (id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {

// if (self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) {

if (self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier]) {

// Initialization code

columns = [[NSMutableArray alloc] initWithCapacity:5];

}

return self;

}

 

 

- (void)addColumn:(CGFloat)position {

 

[columns addObject:[NSNumber numberWithFloat:position]];

}

 

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {

 

[super setSelected:selected animated:animated];

 

// Configure the view for the selected state

}

 

- (void)drawRect:(CGRect)rect { 

if (0 < [columns count]) {

CGContextRef ctx = UIGraphicsGetCurrentContext();

// just match the color and size of the horizontal line

// CGContextSetRGBStrokeColor(ctx, 0.5, 0.5, 0.5, 1.0); 

CGContextSetRGBStrokeColor(ctx, 0, 0, 0, 1.0); 

// CGContextSetLineWidth(ctx, 0.25);

CGContextSetLineWidth(ctx, 0.5);

for (int i = 0; i < [columns count]; i++) {

// get the position for the vertical line

CGFloat f = [((NSNumber*) [columns objectAtIndex:i]) floatValue];

CGContextMoveToPoint(ctx, f, 0);

CGContextAddLineToPoint(ctx, f, self.bounds.size.height);

}

CGContextStrokePath(ctx);

}

[super drawRect:rect];

 

 

- (void)dealloc {

[columns release];

[super dealloc];

}

 

 

@end

 

然后在以下函数中,用MyTableCell替代UITableViewCell

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值