两个控制器的常见tableview

时间:2017-05-18 08:34:43

标签: ios uitableview swift3

我的项目包含dialerViewcontactView

dialerView

class DialerView: UIViewController, UITableViewDelegate, UITableViewDataSource {

var info = Info()
var filterdCells = [CellInfo]()
@IBOutlet weak var inputNumber: UILabel!
@IBOutlet weak var callButton: UIButton!
@IBOutlet weak var backspaceButton: UIButton!
@IBOutlet var keypadSubscript: [UILabel]!
@IBOutlet weak var keypad: UIView!
@IBOutlet weak var contactList: UITableView!


override func viewDidLoad() {
    super.viewDidLoad()
    callButton.layer.cornerRadius = 25
    backspaceButton.isEnabled = false

    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func dialerButtonOp(_ sender: Any) {
    backspaceButton.isEnabled = true
    let button = sender as! UIButton
    inputNumber.text?.append((button.titleLabel?.text)!)
    switch button.title(for: UIControlState.normal)! {
    case "2",
         "3",
         "4",
         "5",
         "6",
         "7",
         "8" ,
         "9":
        let str = computeFilter()
        filterdCells = info.filterSearch(filter: str)
        contactList.reloadData()
    default:
        print ("\(button.title(for: UIControlState.normal)!) is a non-alphabet associated number")
    }

}
@IBAction func backspace(_ sender: UIButton) {
    if inputNumber.text != nil && inputNumber.text != "" {
        inputNumber.text?.remove(at: (inputNumber.text?.index(before: (inputNumber.text?.endIndex)!))!)
    }
    if inputNumber.text == nil || inputNumber.text == "" {
        backspaceButton.isEnabled = false
        filterdCells.removeAll()
        contactList.reloadData()
    } else {
        let str = computeFilter()
        filterdCells = info.filterSearch(filter: str)
        contactList.reloadData()
    }
}

@IBAction func longPress0Recognizer(_ sender: UILongPressGestureRecognizer) {
    if inputNumber.text == nil || inputNumber.text == "" {
        backspaceButton.isEnabled = true
    }
    if sender.state == UIGestureRecognizerState.began {
        inputNumber.text?.append("+")
    }
}

@IBAction func longPressXRecognizer(_ sender: UILongPressGestureRecognizer) {
    if sender.state == UIGestureRecognizerState.began {
        if backspaceButton.isEnabled {
            inputNumber.text = ""
            backspaceButton.isEnabled = false
        }
    }
}

// Remove + signs from filter string
func computeFilter() -> String {
    let str = inputNumber.text!
    var newstr = String()
    for i in 0..<str.characters.count {
        let index = str.index(str.startIndex, offsetBy: i)
        if str[index] != "+" {
            newstr.append(str[index])
        }
    }
    return newstr
}

// Conform to delegate and datasource
func numberOfSections(in tableView: UITableView) -> Int {
    if filterdCells.count == 0 {
        return 0
    } else {
        return 1
    }
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return filterdCells.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    tableView.rowHeight = CGFloat(60)
    tableView.register(UINib(nibName: "ContactCell", bundle: nil), forCellReuseIdentifier: "Contact")
    let cell = tableView.dequeueReusableCell(withIdentifier: "Contact", for: indexPath) as! ContactCell
    cell.nameLabel.text = filterdCells[indexPath.row].name
    cell.numLabel.text = filterdCells[indexPath.row].number
    return cell
}
}

contactView:

class ContactView: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate, NewContactDelegate {

@IBOutlet weak var editList: UIBarButtonItem!
@IBOutlet weak var addressBook: UITableView!
@IBOutlet weak var searchBar: UISearchBar!

var VC: MainViewController? = nil
var showSearchResults = false
var filteredCells = [CellInfo]()

var info = Info()

override func viewDidLoad() {
    super.viewDidLoad()
    searchBar.delegate = self
    searchBar.showsCancelButton = false
    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    info.populateCells()
    if showSearchResults {
        return filteredCells.count
    } else {
        return info.cellInfo.count
    }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    tableView.rowHeight = CGFloat(60)
    tableView.register(UINib(nibName: "ContactCell", bundle: nil), forCellReuseIdentifier: "Contact")
    let cell = tableView.dequeueReusableCell(withIdentifier: "Contact", for: indexPath) as! ContactCell
    if showSearchResults {
        cell.nameLabel.text = filteredCells[indexPath.row].name
        cell.numLabel.text = filteredCells[indexPath.row].number
    } else {
        cell.nameLabel.text = info.cellInfo[indexPath.row].name
        cell.numLabel.text = info.cellInfo[indexPath.row].number
    }
    return cell
}

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if (editingStyle == UITableViewCellEditingStyle.delete) {
        let index: Int?
        if showSearchResults == true {
            index = info.names.index(of: filteredCells[indexPath.row].name)
            filteredCells.remove(at: indexPath.row)
        } else {
            index = info.names.index(of: info.cellInfo[indexPath.row].name)
        }
        info.removeContact (index: index!)
        tableView.reloadData()
    } else if (editingStyle == UITableViewCellEditingStyle.insert) {
        print ("Trying to edit")
    }

}
//Disable deletion capability when not in edit mode
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
    if tableView.isEditing {
        return .delete
    } else {
        return .none
    }
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let editContactVC = EditContact(nibName: "EditContact", bundle: nil)
    editContactVC.delegate = self
    editContactVC.index = indexPath.row
    if showSearchResults {
        editContactVC.name = filteredCells[indexPath.row].name
        editContactVC.number = filteredCells[indexPath.row].number
    } else {
        editContactVC.name = info.cellInfo[indexPath.row].name
        editContactVC.number = info.cellInfo[indexPath.row].number

    }
    self.present(editContactVC, animated: true, completion: nil)
}

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    filteredCells.removeAll()
    filteredCells = info.cellInfo.filter ({ (cell: CellInfo) -> Bool in
        return cell.name.lowercased().contains(searchText.lowercased())
    })

    if searchText != "" {
        showSearchResults = true
    } else {
        showSearchResults = false
    }
    addressBook.reloadData()
}

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    showSearchResults = true
    searchBar.endEditing(true)
    addressBook.reloadData()
}

@IBAction func NewContact(_ sender: UIButton) {
    let addContactVC = AddContact(nibName: "AddContact", bundle: nil)
    addContactVC.delegate = self
    self.present(addContactVC, animated: true, completion: nil)
}

// Add a new contact
func add_Contact(name: String, num: String) {
    info.addContact(name: name, num: num)
    addressBook.reloadData()
}

// Edit existing contact
func edit_Contact(name: String, num: String, index: Int) {
    let arrayIndex:Int?
    if showSearchResults == true {
        arrayIndex = info.names.index(of: filteredCells[index].name)
        filteredCells[index].name = name
        filteredCells[index].number = num
    } else {
        arrayIndex = info.names.index(of: info.cellInfo[index].name)
    }
    info.editContact(name: name, num: num, index: arrayIndex!)
    addressBook.reloadData()
}

// Edit mode to Delete Cells
@IBAction func EditContactList(_ sender: UIBarButtonItem) {
    if let text = editList?.title {
        if text == "Edit" {
            VC?.scrollView?.isScrollEnabled = false
            addressBook.isEditing = true
            editList.title = "Done"
        } else {
            VC?.scrollView?.isScrollEnabled = true
            addressBook.isEditing = false
            editList.title = "Edit"
        }
    }
}   
}

Info

class Info {
var cellInfo = [CellInfo]()
var names = ["R", "R", "S", "P", "M", "V", "M", "S"]
var numbers = ["9830000001", "9830000002", "9830000003", "9830000004",
               "9830000005", "9830000006", "9830000007", "9830000008"]

let dict:[Int: [String]] = [2: ["A", "B", "C"], 3: ["D", "E", "F"], 4: ["G", "H", "I"],
                            5: ["J", "K", "L"], 6: ["M", "N", "O"], 7: ["P", "Q", "R", "S"],
                            8: ["T", "U", "V"], 9: ["W", "X", "Y", "Z"]]

// Compute keypad combinaton for names
func computeNameCode(name: String) -> String {
    var nameCode = ""
    for j in 0..<name.characters.count {
        let index = name.index(name.startIndex, offsetBy: j)
        let ch = name[index]
        //print (ch)
        nameCode.append(findKey(ch: ch))
    }
    return nameCode
}

// Find key value for character
func findKey (ch: Character) -> String {
    for (key, array) in dict {
        if (array.contains(ch.description)) {
            //print ("Key for \(ch) is \(key)")
            return key.description
        }
    }
    return ""
}

func populateCells() {
    cellInfo.removeAll()
    for i in 0..<names.count {
        var objCellInfo = CellInfo ()
        objCellInfo.name = names[i]
        objCellInfo.number = numbers[i]
        objCellInfo.nameCode = computeNameCode(name: names[i].uppercased())
        cellInfo.append(objCellInfo)
    }
    cellInfo.sort(by: sortNames)
}

// func sortNames
func sortNames ( name1: CellInfo, name2: CellInfo ) -> Bool {
    return name1.name.uppercased() < name2.name.uppercased()
}

func filterSearch(filter: String) -> [CellInfo] {
    populateCells()
    return (cellInfo.filter ({ (cell: CellInfo) -> Bool in
        return cell.nameCode.lowercased().contains(filter.lowercased())
    }))
}

func addContact(name: String, num: String) {
    names.append(name)
    numbers.append(num)
}

func editContact(name: String, num: String, index:Int ) {
    names[index] = name
    numbers[index] = num
}

func removeContact(index: Int) {
    names.remove(at: index)
    numbers.remove(at: index)
}
}

我的结构:

struct CellInfo {
    var name:String = ""
    var number:String = ""
    var nameCode:String = ""
}

这两个视图都加载到支持分页的scrollView上。因此,加载的第一个视图是DialerView,在向右滚动时,我会看到ContactView

我想要做的是使用namecode中的ContactView来过滤我的结果,并将其显示在DialerView中的UITable中,而无需重写所有代码。在DialerView中使用我的InputNumber UIlabel(名为addressBook)作为我的UItable(名为ContactView)的搜索参数并在{中显示已过滤的单元格的最佳方式{1}}(位于拨号器上方的表格中)

什么是DialerView

namecode包含已保存联系人姓名的拨号程序组合(请在namecode中查看dict,这应该说清楚。)

我想要实现的目标:

John的名称代码为 - &gt; 5646.所以当我在ContactView上输入5/56/564/5646时,John应该显示为我可以在拨号器上方的UITableView中调用的预先保存的联系人

修改:我创建了一个名为DialerView的新课程,并将我的数据及其操作添加到课程中。 InfoDialerView都使用ContactView的对象,但如何让他们使用 SAME 对象来提供数据一致性?
目前,如果我添加了新的联系人(Info中提供的功能),则它不会在我的ContavtView上显示为搜索结果。它只读取预定义数据。

谢谢。

2 个答案:

答案 0 :(得分:0)

你必须将dataSource存储在两个类都可以访问的地方(比如单例类/数据库/ NSUserDefault),然后只需将它取出来过滤/使用它们

在您的示例中,所有联系人都包含在ContactView课程中,您必须将namenumber数组移到该课程之外,或者DialerView必须持有ContactView的实例来访问它们,最简单的方法是创建一个单例来容纳那2个数组

答案 1 :(得分:0)

您必须添加UIView类型类,并且在此类中,您必须添加表视图及其委托/数据源方法。并添加协议(创建自定义委托方法),以便在您想要添加此tableview时使用,表示contactview和declairview

修改

<强> Contact.h

#import <UIKit/UIKit.h>

@class Contact;
@protocol ContactTableDelegate <NSObject>

@optional
- (void)didSelectRowForContact:(Contact *)contact atIndexPath:(NSIndexPath *)indexPath;

@end
@interface ContactTableView : UIView

@property (nonatomic, weak) id<ContactTableDelegate>            delegate;
@property (nonatomic, strong) NSArray                           *tableData;
@property (nonatomic, strong) Contact                           *selectedContactForFirstSelectedVC;

- (void)keyboardWillDisplay;
- (void)keyboardwillHide;
- (void)actionRefresh:(UIButton *)button;

@end

<强> Contact.M

#import "ContactTableView.h"
#import "Contact.h"
#import "Utility.h"
#import "FontUtility.h"
#import "StyleDefinitions.h"
#import "AsyncImageView.h"
#import "GetContactsFromDevice.h"
#import "DataHandler.h"
#import <AddressBookUI/AddressBookUI.h>
#import "FirstSelectedMatchMakeViewController.h"
#import "Constants.h"

@interface ContactTableView () < UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,ABNewPersonViewControllerDelegate > {
    UITableView             *contactTableView;
    NSMutableDictionary     *sections;
    NSArray                 *sectionTitles;
    NSArray                 *indexTitles;
    NSArray                 *searchResults;
    BOOL                    isSearchBarOn;
    UITextField             *searchBar;
}

@end

@implementation ContactTableView
@synthesize tableData;
@synthesize selectedContactForFirstSelectedVC;

- (void)awakeFromNib {
    [self setBackgroundColor:[UIColor colorWithRed:233.0/255.0 green:233.0/255.0 blue:233.0/255.0 alpha:1.0]];
    [self setupViews];
}

- (void)setupViews {

    //Setup Search Bar
    searchBar = [[UITextField alloc] initWithFrame:CGRectMake(10, 10, self.bounds.size.width - 20, 30)];
    searchBar.autoresizingMask = UIViewAutoresizingFlexibleWidth;

    searchBar.delegate = self;
    searchBar.background = kImageSearchBG;
    searchBar.placeholder = @"Search";
    [self addSubview:searchBar];

    UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    UIImageView *searchImage = [[UIImageView alloc]initWithFrame:CGRectMake(8, 8, 14, 14)];
    searchImage.image = kImageSearchIcon;
    paddingView.backgroundColor = [UIColor clearColor];
    [paddingView addSubview:searchImage];
    searchBar.leftView = paddingView;
    searchBar.leftViewMode = UITextFieldViewModeAlways;

    contactTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, searchBar.frame.size.height + searchBar.frame.origin.y + 10, self.frame.size.width, self.frame.size.height - searchBar.frame.size.height-20-40)];
    contactTableView.delegate = self;
    contactTableView.dataSource = self;
    contactTableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    contactTableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
    contactTableView.sectionIndexBackgroundColor = [UIColor clearColor];
    [self addSubview:contactTableView];
    contactTableView.sectionIndexColor = [UIColor colorWithRed:105.0/255.0 green:240.0/255.0 blue:174.0/255.0 alpha:1.0];
    [contactTableView setBackgroundColor:[UIColor colorWithRed:243.0/255.0 green:243.0/255.0 blue:243.0/255.0 alpha:1.0]];

    contactTableView.tableFooterView  = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.frame.size.width, 0.0f)];
    contactTableView.tableFooterView.autoresizingMask = UIViewAutoresizingFlexibleWidth;

    indexTitles = @[@"A", @"B", @"C", @"D", @"E", @"F", @"G", @"H", @"I", @"J", @"K", @"L", @"M", @"N", @"O", @"P", @"Q", @"R", @"S", @"T", @"U", @"V", @"W", @"X", @"Y", @"Z"];

    // Add New and Refresh option
    [self setContactTableOptions];
}

#pragma - 
#pragma - Add New and Refresh Actions

- (void)setContactTableOptions {

    CGSize screenSize          = [UIScreen mainScreen].bounds.size;
    CGFloat currentViewHeight   = screenSize.height - self.frame.origin.y;

    // inserting add new and refresh buttons

    UIButton *buttonAddNew = [[UIButton alloc] initWithFrame:CGRectMake(0, currentViewHeight-40, kScreenSize.width/2-1, 40)];
    [buttonAddNew setTitle:kAddNew forState:UIControlStateNormal];
    [buttonAddNew addTarget:self action:@selector(actionAddNew:) forControlEvents:UIControlEventTouchUpInside];
    [buttonAddNew setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [buttonAddNew.titleLabel setFont:[FontUtility semiBoldFontWithSize:16.0]];
    [buttonAddNew.titleLabel setTextAlignment:NSTextAlignmentCenter];
    [buttonAddNew setBackgroundColor:[UIColor whiteColor]];
    [self addSubview:buttonAddNew];

    UIButton *buttonRefresh = [[UIButton alloc] initWithFrame:CGRectMake(kScreenSize.width/2+1, currentViewHeight-40, kScreenSize.width/2-1, 40)];
    [buttonRefresh setTitle:kRefresh forState:UIControlStateNormal];
    [buttonRefresh addTarget:self action:@selector(actionRefresh:) forControlEvents:UIControlEventTouchUpInside];
    [buttonRefresh setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [buttonRefresh.titleLabel setFont:[FontUtility semiBoldFontWithSize:16.0]];
    [buttonRefresh.titleLabel setTextAlignment:NSTextAlignmentCenter];
    [buttonRefresh setBackgroundColor:[UIColor whiteColor]];
    [self addSubview:buttonRefresh];
}


- (void)newPersonViewController:(ABNewPersonViewController *)newPersonView didCompleteWithNewPerson:(ABRecordRef)person {
    UIViewController *vc = [Utility traverseResponderChainForUIViewController:self];
    [vc dismissViewControllerAnimated:YES completion:nil];
    [self actionRefresh:nil];
}


- (void)actionAddNew:(UIButton *)button {
    ABNewPersonViewController *picker   = [[ABNewPersonViewController alloc] init];

    UIViewController *vc = [Utility traverseResponderChainForUIViewController:self];
    picker.newPersonViewDelegate        = self;

    UINavigationController *navigation  = [[UINavigationController alloc] initWithRootViewController:picker];
    [vc presentViewController:navigation animated:YES completion:nil];
}

- (void)actionRefresh:(UIButton *)button {
    button.userInteractionEnabled = NO;
    [self showLoadingOnWindow];
    [GetContactsFromDevice refreshAllContactsInfo:^(BOOL flag) {
        button.userInteractionEnabled = YES;

        if ([[Utility traverseResponderChainForUIViewController:self] isKindOfClass:[FirstSelectedMatchMakeViewController class]]) {
            NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"self.recordID != %d",selectedContactForFirstSelectedVC.recordID];
            self.tableData = [[DataHandler sharedInstance].deviceContactList filteredArrayUsingPredicate:resultPredicate];
        } else {
            self.tableData = [DataHandler sharedInstance].deviceContactList;
        }
        [self performSelectorOnMainThread:@selector(hideLoadingView) withObject:nil waitUntilDone:YES];

    } failure:^(NSError *error) {
        [self performSelectorOnMainThread:@selector(hideLoadingView) withObject:nil waitUntilDone:YES];
    }];
}

- (void)hideLoadingView {
    [self hideLoadingFromWindow];
}

- (void)setTableData:(NSArray *)aTableData {
    tableData = aTableData;
    [self organizeData];
    searchBar.text = @"";
    isSearchBarOn = false;
    //relaod table instantly
    [contactTableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];

}

- (void)setSelectedContactForFirstSelectedVC:(Contact *)aContact {
    selectedContactForFirstSelectedVC = aContact;
}

- (void)organizeData {
    sections = [NSMutableDictionary dictionary];
    for (Contact *contact in tableData) {
        NSString *c = [[contact.name substringToIndex:1] uppercaseString];
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains[c] %@", c]; // if you need case sensitive search avoid '[c]' in the predicate
        NSArray *results = [sections.allKeys filteredArrayUsingPredicate:predicate];
        if (results.count == 0)
            [sections setValue:[NSMutableArray array] forKey:c];
    }

    for (Contact *contact in tableData) {
        NSString *temp = contact.name;
        [[sections objectForKey:[[temp substringToIndex:1] uppercaseString]] addObject:contact];
    }
    sectionTitles = [[sections allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
}


- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope {
    //predicate for searching specific data
    NSPredicate *namePredicate = [NSPredicate predicateWithFormat:@"self.name contains[c] %@", searchText];
    NSPredicate *emailPredicate = [NSPredicate predicateWithFormat:@"self.primaryEmail contains[c] %@", searchText];

    NSPredicate *compoundPredicate = [NSCompoundPredicate orPredicateWithSubpredicates:@[namePredicate, emailPredicate]];
    searchResults = [tableData filteredArrayUsingPredicate:compoundPredicate];

    [contactTableView reloadData];
}

- (void)keyboardWillDisplay {
    // write code here for table hight
    contactTableView.frame = CGRectMake(contactTableView.frame.origin.x, contactTableView.frame.origin.y,
                                        contactTableView.frame.size.width,  contactTableView.frame.size.height-215);
}


- (void)keyboardwillHide {

    contactTableView.frame = CGRectMake(contactTableView.frame.origin.x, contactTableView.frame.origin.y,
                                        contactTableView.frame.size.width,  contactTableView.frame.size.height+215);
}

#pragma mark-
#pragma mark- TextField and Search  methods
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    return [textField resignFirstResponder];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (![[textField.text stringByReplacingCharactersInRange:range withString:string] isEqualToString:@""]) {
        isSearchBarOn = true;
        [self filterContentForSearchText:[textField.text stringByReplacingCharactersInRange:range withString:string] scope:[textField.text stringByReplacingCharactersInRange:range withString:string]];
    } else {
        isSearchBarOn = false;
        [contactTableView reloadData];
    }
    return YES;
}




#pragma mark-
#pragma mark- Table methods

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {

    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (isSearchBarOn)
        return 1;
    return [sectionTitles count];
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (isSearchBarOn)
        return nil;

    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 22)];
    view.backgroundColor = [UIColor colorWithRed:233.0/255.0 green:233.0/255.0 blue:233.0/255.0 alpha:1.0];
    UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, tableView.frame.size.width-10,view.frame.size.height)];
    lable.text = [sectionTitles objectAtIndex:section];
    [view addSubview:lable];
    return view;
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    if (isSearchBarOn)
        return nil;
    return indexTitles;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    if (isSearchBarOn)
        return 0;
    return [sectionTitles indexOfObject:title];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (isSearchBarOn)
        return [searchResults count];
    return  [[sections valueForKey:[[[sections allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)] objectAtIndex:section]] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kContactCellIdentifier];
    if (cell == nil) {
        // Load the top-level objects from the custom cell XIB.
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:kContactCellIdentifier owner:self options:nil];
        // Grab a pointer to the first object (presumably the custom cell, as that's all the XIB should contain).
        cell = [topLevelObjects objectAtIndex:0];
        cell.backgroundColor = [UIColor colorWithRed:243.0/255.0 green:243.0/255.0 blue:243.0/255.0 alpha:1.0];
        cell.clipsToBounds = YES;
    }

    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];

    UIImageView *cellImg = (UIImageView *)[cell viewWithTag:1];
    UILabel *lblCellName = (UILabel *)[cell viewWithTag:2];
    UILabel *lblCellEmail = (UILabel *)[cell viewWithTag:3];

    cellImg.layer.cornerRadius     = cellImg.frame.size.width / 2;
    cellImg.layer.borderWidth      = 1.0;
    cellImg.layer.borderColor      = (__bridge CGColorRef)([UIColor clearColor]);
    cellImg.clipsToBounds          = YES;

    if (isSearchBarOn) {
        Contact *contact = [searchResults objectAtIndex:indexPath.row];

        if (contact.recordID) {

            if (![Utility imageForContactId:contact.recordID]) {
                cellImg.image = kImageUserIcon;
            } else {
                [cellImg setImage:[Utility imageForContactId:contact.recordID]];
            }

        } else {

            if (contact.imageURL.length<=0) {
                cellImg.image = kImageUserIcon;
            } else {
                cellImg.imageURL = [NSURL URLWithString:contact.imageURL];
            }
        }

        [lblCellName setText:contact.name];
        [lblCellEmail setText:[[contact.email componentsSeparatedByString:@","] firstObject]];

    } else {

        Contact *contact = [[sections valueForKey:[[[sections allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)] objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];


        if (contact.recordID > 0) {

            if (![Utility imageForContactId:contact.recordID]) {
                cellImg.image = kImageUserIcon;
            } else {
                [cellImg setImage:[Utility imageForContactId:contact.recordID]];
            }
        } else {

            if (contact.imageURL.length<=0) {
                cellImg.image = kImageUserIcon;
            } else {
                cellImg.imageURL = [NSURL URLWithString:contact.imageURL];
            }
        }

        [lblCellName setText:contact.name];
        [lblCellEmail setText:[[contact.email componentsSeparatedByString:@","] firstObject]];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if([self.delegate respondsToSelector:@selector(didSelectRowForContact:atIndexPath:)]) {
        if (isSearchBarOn) {
            [self.delegate didSelectRowForContact:searchResults[indexPath.row] atIndexPath:indexPath];
            [searchBar endEditing:YES];
        } else {
            [self.delegate didSelectRowForContact:[sections objectForKey:sectionTitles[indexPath.section]][indexPath.row] atIndexPath:indexPath];
        }
        searchBar.text = @"";
        [tableView reloadData];
    }

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 88.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 22.0;
}

#pragma - 
#pragma - Dealloc Method

- (void)dealloc {

    selectedContactForFirstSelectedVC       = nil;
    contactTableView                        = nil;
    sections                                = nil;
    sectionTitles                           = nil;
    indexTitles                             = nil;
    searchResults                           = nil;
    isSearchBarOn                           = nil;
    searchBar                               = nil;
    tableData                               = nil;

}

@end

现在步骤

  • 现在,您必须在故事板上添加一个包含联系人类的视图。
  • 在viewcontroller上添加要添加此表的插座
  • 之后,你必须设置委托你想要添加这个表的地方,如下所示:

    @property(弱,非原子)IBOutlet ContactTableView * contactTableView;

    self.contactTableView.delegate = self;

    self.contactTableView.tableData = table_data;