我創建了一個自定義表格視圖單元格,其上有一個按鈕,並在同一個文件tableviewcell.m(基本calsee UITableViewCell)中的按鈕targetof。如何從發件人的選項中獲得值選項
當我點擊按鈕然後行動被調用。
我要做的是從該按鈕的發件人選項中獲取值。如圖所示想要獲取「badgename」的值。
我創建了一個自定義表格視圖單元格,其上有一個按鈕,並在同一個文件tableviewcell.m(基本calsee UITableViewCell)中的按鈕targetof。如何從發件人的選項中獲得值選項
當我點擊按鈕然後行動被調用。
我要做的是從該按鈕的發件人選項中獲取值。如圖所示想要獲取「badgename」的值。
你可以這樣做
UITableViewCell *cell = (UITableViewCell *)[button superView] superView];
那麼你可以得到你的對象是這樣
UILabel *label = (UILabel *)[cell viewWithTag:1234];
請不要這樣做。 –
是否有任何問題...請告訴我,以便我可以更新自己。 –
看看我的答案,我會擴展它。 –
首先,在按鈕動作得到全細胞,轉換點按鈕到tableview的indexPath,那麼你可以使用該indexPath從你的數據數組中獲取值,甚至可以從單元格中獲取數值
CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
if (indexPath != nil)
{
//Do stuff with the data array
//Object *obj = [dataArray objectAtIndex:indexPath.row]
//Get the text from the array
//OR
//YourCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
//NSString *labelString = cell.textLabel.text;
}
Donot在tablviewcell.m文件中創建目標方法。只需創建一個按鈕的出口並在基本控制器中添加目標,從創建表的位置開始並按照描述的過程進行操作。
在你的cellForRowAtIndexPath:方法給按鈕標籤與indexPath.row和按鈕的操作方法只是獲取標記,並調用的cellForRowAtIndexPath得到cell.By細胞可以獲取
-(void)BtnOfCellTapped:(id)sender
{
UIButton *btn = (UIButton*)sender;
CustomCell *cell = (CustomCell*)[tblView cellForRowAtIndexPath:btn.tag];
NSLog(@"%@",cell.badgeValue);
}
你認爲會發生什麼,如果表有更多的一個部分 – sage444
你應該當你想要的所有值跟蹤來自單元格的一些其他事件,而不僅僅是默認選擇。例如你添加一些按鈕。
UIView
的tag
屬性是壞! 用標籤閱讀代碼並不容易。當你不僅有行而且還有段時,你會做什麼?UITableViewCell
作爲 superview
您的按鈕是不好太! 按鈕可以直接添加爲UITableViewCell
子視圖或作爲單元的contentView
子視圖。那麼我們該怎麼辦?我們應該遵循委託模式。它的好也縮放。您可以將鏈接存儲到您的單元格中的任何數據。
您單元的標題:
@class CellWithButton;
@protocol CellWithButtonDelegate <NSObject>
- (void)cellWithButtonDidPressed:(CellWithButton *)cell;
@end
@interface CellWithButton : UITableViewCell
@property id anyData;
@property (nonatomic, weak) id <CellWithButtonDelegate> *delegate;
@end
您單元的實現:
- (void)buttonPressed:(id)sender
{
[self.delegate cellWithButtonDidPressed:self];
}
現在你的控制器:
- (UITableViewCell *)tableView cellFor...
{
CellWithButton *cell = ...;
cell.anyData = myData;
cell.delegate = self;
}
- (void)cellWithButtonDidPressed:(CellWithButton *)cell
{
id myData = cell.anyData;
// Wow! Now you have your data.
// And you can even find `indexPath` for your cell
// by calling [self.tableView indexPathForCell:cell].
}
您可以使用關聯的對象這一點。
如何使用關聯的對象?
要設置屬性
objc_setAssociatedObject(self, @"AnyString", object, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
要獲取屬性
objc_getAssociatedObject(self,@"AnyString");
你有沒有讀過反模式部分? –
ü希望的是得到的值標籤在包含該按鈕的單元格中,我是否正確? – Tj3n
是的,我想獲得標籤名稱「badgesname」的價值 –
哦,我的..分開存儲所有東西。你應該做的是休閒委派模式,並將數據保存在單元格中。然後,當按下按鈕時,可以使用self(從單元格)和單元格外部調用委託方法,以獲取單元格的數據。 –