在寫項目時候,tableView的分割線一般都會自定義,我采取的方法是為UITableView額外的添加一個叫
- (BOOL)tableView:(UITableView *)tableView borderForRowAtIndexPath:(NSIndexPath *)indexPath;
的協(xié)議方法,說起這個協(xié)議方法,我一般都是在搭建項目框架時候,會寫一個tableView的基類,也會自定義一個cell的基類,在基類中制定一個繼承于UITableViewDataSource, UITableViewDelegate的協(xié)議,然后在子類中重載tableView的協(xié)議方法,而上面的borderForRowAtIndex:就是這個協(xié)議的協(xié)議方法,在tableView的基類.h文件中代碼:
?@protocol CardViewDelegate;?
?@interface CardView : UITableView
?@property (nonatomic, assign)idcardViewDelegate;?
?@end?
?@protocol CardViewDelegate
這個borderForRowAtIndex:方法的實現(xiàn):
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
?{
? ? ?UITableViewCell *cell = nil;
? ? ?if (self.cardViewDelegate && [self.cardViewDelegate respondsToSelector:@selector(tableView:cellForRowAtIndexPath:)]) {
? ? ? ? cell = [self.cardViewDelegate tableView:tableView cellForRowAtIndexPath:indexPath];
? ? ?}
? ? ?if ([cell isKindOfClass:[CardCell class]]) {
? ? ? ? ?CardCell *cardCell = (CardCell *)cell;
? ? ? ? ?BOOL border = YES;
?? ? ? ? if (self.cardViewDelegate && [self.cardViewDelegate respondsToSelector:@selector(tableView:borderForRowAtIndexPath:)]) {
? ? ? ? ? ? ?border = [self.cardViewDelegate tableView:tableView borderForRowAtIndexPath:indexPath];
? ? ? ? ?}
? ? ? ? ?cardCell.borders = border;
? ? ?}
? ? ?return cell;
?}
在自定義cell基類中,實現(xiàn)如下代碼:
?- (void)drawRect:(CGRect)rect {
? ? ?CGContextRef context = UIGraphicsGetCurrentContext();
? ? ?if (self.borders == YES) {
? ? ? ? CGContextMoveToPoint(context, CGRectGetMinX(rect) + 10, CGRectGetMaxY(rect));
?? ? ? ? CGContextAddLineToPoint(context, CGRectGetMaxX(rect) - 10, CGRectGetMaxY(rect));
? ? ?}
? ? else if (self.borders == NO){
? ? ?}
? ? ?CGContextSetStrokeColorWithColor(context, [[UIColor blackColor] CGColor] );
? ? ?CGContextSetLineWidth(context, 0.5f);
? ? ?CGContextStrokePath(context);
?}
?- (void)setBorders:(BOOL)borders {
? ? ?if (_borders != borders) {
? ? ? ? ?_borders = borders;
? ? ? ? ?[self setNeedsDisplay];
? ? ?}
?}
那么在當(dāng)前的UITableView中,去重載borderForRowAtIndex:方法:
?- (BOOL)tableView:(UITableView *)tableView borderForRowAtIndexPath:(NSIndexPath *)indexPath {
? ? if (indexPath.row == 0) {
? ? ? ? return YES;
? ? ?}
? ? ?else {
? ? ? ? ?return NO;
? ? ?}
?}
到這里,設(shè)置indexPath的值,就可以控制哪個cell的分割線是否出現(xiàn),其實這種做法是簡易的去返回BOLL的YES或NO去實現(xiàn),那么我在實際項目中不會這么寫,因為單單的YES or NO太單一了,我會寫成
?- (NSInteger)tableView:(UITableView *)tableView borderForRowAtIndexPath:(NSIndexPath *)indexPath;
其中它返回的值是枚舉類型
?typedef NS_ENUM(NSInteger, Border) {
? ? ?TOP = 0x00000001,
? ? ?LEFT = 0x00000002,
? ? ?RIGHT = 0x00000004,
? ? ?BOTTOM = 0x00000008,
? ? ?TOP_WITH_MARGIN = 0x00000010,
? ? ?BOTTOM_WITH_MARGIN = 0x00000020,
? ? ?NONE = 0x10000000,
?};
這樣的寫法無疑可以設(shè)置的余地大大增加了