UITableview: How to Disable Selection for Some Rows but Not Others
I am displaying in a group tableview
contents parsed from XML. I want to disable the click event on it (I should not be able to click it at all) The table contains two groups. I want to disable selection for the first group only but not the second group. Clicking the first row of second group navigates
to my tube player view
.
How can I make just specific groups or rows selectable?
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if(indexPath.section!=0)
if(indexPath.row==0)
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:tubeUrl]];
}
Thanks.
You just have to put this code into cellForRowAtIndexPath
To disable the cell's selection property:
(While tapping the cell).
cell.selectionStyle = UITableViewCellSelectionStyle.none
To enable being able to select (tap) the cell:
(tapping the cell).
// Default style
cell.selectionStyle = UITableViewCellSelectionStyle.blue
// Gray style
cell.selectionStyle = UITableViewCellSelectionStyle.gray
Note that a cell with selectionStyle = UITableViewCellSelectionStyleNone
will still cause the UI to call didSelectRowAtIndexPath
when touched by the user. To avoid this, do as suggested below and set.
cell.userInteractionEnabled = false
instead. Also note you may want to set cell.textLabel.enabled = false
to grey out the item.
If you want to make a row (or subset of rows) non-selectable, implement the UITableViewDelegate method -tableView:willSelectRowAtIndexPath: (also mentioned by TechZen). If the indexPath should be not be selectable, return nil, otherwise return the indexPath. To get the default selection behavior, you just return the indexPath passed to your delegate method, but you can also alter the row selection by returning a different indexPath.
example:
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// rows in section 0 should not be selectable
if ( indexPath.section == 0 ) return nil;
// first 3 rows in any section should not be selectable
if ( indexPath.row <= 2 ) return nil;
// By default, allow row to be selected
return indexPath;
}
Starting in iOS 6, you can use
-tableView:shouldHighLightRowAtIndexPath:
If you return NO
, it disables both the selection highlighting and the storyboard triggered segues connected to that cell.
The method is called when a touch comes down on a row. Returning NO
to that message halts the selection process and does not cause the currently selected row to lose its selected look while the touch is down.
UITableViewDelegate Protocol Reference
链接地址: http://www.djcxy.com/p/49402.html