iOS_在UITableViewCell按鈕點擊處理中使用Runtime

  • 一直都覺得Runtime博大精深,但也越想逐步學(xué)習(xí)和使用.今天記錄下在項目開發(fā)中的一點小應(yīng)用.
  • 實現(xiàn)了點擊事件可以將指定Model傳到函數(shù)中,特定情境更方便處理.

1.頭文件以及靜態(tài)字符串

  #import <objc/runtime.h>

  static const  NSString *lala;

2.在CellforRow(TableView代理方法)中使用

  -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  {
  //根據(jù)指定的下標從數(shù)組取出要用的Model
  NSArray *dayArr = _totalDataArray[chosedWeekNum];
  LDJSchoolCarCheckModel  *model = dayArr[indexPath.section];
  LDJSchoolCarBabyModel *babyModel = model.content[indexPath.row];
    ...
    objc_setAssociatedObject(cell.phoneButton, &lala, babyModel, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    objc_setAssociatedObject(cell.upAndDownButton, &lala, babyModel, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  //上面其實有兩個button都做了處理,為了簡介下面只展開一個
  [cell.phoneButton addTarget:self action:@selector(callPhoneButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    ...
  }

3.使用

   - (void)callPhoneButtonClick:(UIButton *)btn{
  //取出要用的model
  LDJSchoolCarBabyModel *babyModel = objc_getAssociatedObject(btn, &lala);
  //賦給全局的model,另一個方法可以直接用
  currentModel = babyModel;
  UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:[NSString stringWithFormat:@"呼叫%@?",babyModel.name] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"確定", nil];
  alert.tag = 5000;
  [alert show];
  }
  - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  {
  if(alertView.tag == 5000 && buttonIndex == 1){
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",currentModel.primary_mobile]]];
    }
  }
  • 以上通過使用objc_getAssociatedObject(屬性擴展)實現(xiàn)了通過點擊cell上的電話按鈕撥打指定號碼.
    歡迎交流.
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容