最后,问题不在于 cellForRowAtIndexPath: 方法,而在于 setAccessoryViewForCell: 方法。在创建包含两个按钮作为子视图的视图时,我真的不应该对框架使用文字值。我没有为附件视图属性设置视图,而是重写了整个 cellForRowAtIndexPath: 方法,并将子视图添加到单元格的 contentView。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier = @"notificationsCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (!cell){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
}
PFObject *user = [self.objects objectAtIndex:indexPath.row];
NSString *firstName = [user objectForKey:@"firstName"];
NSString *lastName = [user objectForKey:@"lastName"];
cell.textLabel.text = [NSString stringWithFormat:@"%@ %@", firstName, lastName];
UIView *view = [UIView new];
view.frame = CGRectMake(230, 2, 80, 40);
view.backgroundColor = [UIColor whiteColor];
UIButton *acceptButton = [UIButton buttonwithType:UIButtonTypeCustom];
UIButton *declineButton = [UIButton buttonWithType:UIButtonTypeCustom];
[acceptButton setTitle:@"" forState:UIControlStateNormal];
[declineButton setTitle:@"" forState:UIControlStateNormal];
[acceptButton setImage:[UIImage imageNamed:@"Ok.png"] forState:UIControlStateNormal];
[declineButton setImage:[UIImage imageNamed:@"Close.png"] forState:UIControlStateNormal];
[acceptButton addTarget:self action:@selector(acceptButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
[declineButton addTarget:self action:@selector(declineButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
acceptButton.frame = CGRectMake(CGRectGetMinX(view.bounds), CGRectGetMinY(view.bounds), CGRectGetWidth(view.bounds)/2, CGRectGetHeight(view.bounds));
declineButton.frame = CGRectMake(CGRectGetMidX(view.bounds), CGRectGetMinY(view.bounds), CGRectGetWidth(view.bounds)/2, CGRectGetHeight(view.bounds));
[view addSubview:acceptButton];
[view addSubview:declineButton];
[cell.contentView addSubview:view];
return cell;
}
主要区别在于,在为每个按钮设置框架时,我使用了文字值(不是一个好习惯),现在我使用了 CGRect 函数 CGRectGetMinX(CGRect rect)、CGRectGetMinY(CGRect rect)、CGRectGetWidth(CGRect rect)、CGRectGetMidX( CGRect rect) 和 CGRectGetHeight(CGRect rect) 以获得更准确的值来设置每个按钮的框架。这是对 UIView 框架如何工作的误解,我建议始终使用这些函数来获取子视图的原点和大小,而不是使用文字值。