码迷,mamicode.com
首页 > 移动开发 > 详细

IOS 通过button获取cell

时间:2014-09-10 20:57:30      阅读:260      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   使用   2014   div   问题   

在使用tableview时,有时我们需要在cell中添加button和label,以便添加某项功能,而且往往点这个button的方法中需要知道button所在cell中label内存放的值。

一般而言我们可以用tag来做,但当table有很多行的时候,设置tag就没有那么方便了,这里我介绍另外一种方法。

我们知道IOS里每一个视图都有父视图,那我们可不可以用这个方法获取cell呢?

经过一番查找测试发现superview方法可以找到button所在cell

给button写上这样的方法

-(void)btn_Onclick:(id)sender
{
    UIButton *btn = (UIButton *)sender;
    
    NSLog(@" [btn superview] =  %@ ",[[btn superview]class]);
    NSLog(@" [[[btn superview]superview]class] = %@",[[[btn superview]superview]class]);
}

输出结果如下

2014-09-10 19:09:42.203 superview[4720:60b]  [btn superview] =  UITableViewCellScrollView 
2014-09-10 19:09:42.646 superview[4720:60b]  [[[btn superview]superview]class] = UITableViewCell

说明这样没问题。但经过我的测试发现,对于自己写的继承自uitableviewcell的类,(这里我是SongTableViewCell)需要稍作修改。

    NSLog(@" [btn superview] =  %@ ",[[btn superview]class]);
    NSLog(@" [[[btn superview]superview]class] = %@",[[[btn superview]superview]class]);
    NSLog(@" [[[btn superview]superview]superview]class] = %@",[[[[btn superview]superview]superview] class]);

输出结果如下:

2014-09-10 18:54:50.036 Music_Player[4451:60b]  [btn superview] =  UITableViewCellContentView 
2014-09-10 18:54:50.036 Music_Player[4451:60b]  [[[btn superview]superview]class] = UITableViewCellScrollView
2014-09-10 18:54:50.036 Music_Player[4451:60b]  [[[btn superview]superview]superview]class] = SongTableViewCell

PS:对于viewwithtag方法多说一句,这个方法不能寻找tag为0的控件,就算自己button的tag为0也无法找到,猜测是与系统默认的空间重复。

IOS 通过button获取cell

标签:style   blog   color   io   os   使用   2014   div   问题   

原文地址:http://www.cnblogs.com/myqiqiang/p/3965023.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!