2016-05-05 2 views
0

Я пытаюсь реализовать табличный вид в swipeable в моем проекте Swift 2, Xcode 7.Попытка реализовать MGSwipeTableCell в представлении таблицы iOS

Я хочу использовать эту библиотеку:

https://github.com/MortimerGoro/MGSwipeTableCell

Я просто пытаюсь выяснить, как правильно реализовать это в моем проекте.

У меня есть UIView с TableView внутри него, а также обычай TableViewCell

Вот код реализации согласно GitHub репо:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell 
{ 
let reuseIdentifier = "programmaticCell" 
var cell = self.table.dequeueReusableCellWithIdentifier(reuseIdentifier) as! MGSwipeTableCell! 
if cell == nil 
{ 
    cell = MGSwipeTableCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: reuseIdentifier) 
} 

cell.textLabel!.text = "Title" 
cell.detailTextLabel!.text = "Detail text" 
cell.delegate = self //optional 

//configure left buttons 
cell.leftButtons = [MGSwipeButton(title: "", icon: UIImage(named:"check.png"), backgroundColor: UIColor.greenColor()) 
    ,MGSwipeButton(title: "", icon: UIImage(named:"fav.png"), backgroundColor: UIColor.blueColor())] 
cell.leftSwipeSettings.transition = MGSwipeTransition.Rotate3D 

//configure right buttons 
cell.rightButtons = [MGSwipeButton(title: "Delete", backgroundColor: UIColor.redColor()) 
    ,MGSwipeButton(title: "More",backgroundColor: UIColor.lightGrayColor())] 
cell.rightSwipeSettings.transition = MGSwipeTransition.Rotate3D 

return cell 
} 

Вот является cellForRowAtIndexPath FUNC в моем текущем проекте:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 

    let post = posts[indexPath.row] 

    if let cell = tableView.dequeueReusableCellWithIdentifier("PostCell") as? PostCell { 

     cell.request?.cancel() 

     var img: UIImage? 

     if let url = post.imageUrl { 
      img = FeedVCViewController.imageCache.objectForKey(url) as? UIImage 
     } 

     cell.configureCell(post, img: img) 

     return cell 
    } else { 
     return PostCell() 
    } 
} 

мне нужно реализовать эту функцию обратного вызова:

MGSwipeButton(title: "Delete", backgroundColor: UIColor.redColor(), callback: { 
    (sender: MGSwipeTableCell!) -> Bool in 
    println("Convenience callback for swipe buttons!") 
    return true 
}) 

Может ли кто-нибудь вести меня в правильном направлении, как это сделать? Я просто пытаюсь сохранить себе большую головную боль, поскольку я новичок в развитии мобильных устройств.

Я в основном смущен объявлением «ячейки» и выражением «если» в коде реализации и как объединить его с созданной мной ячейкой.

Спасибо заранее!

+0

Вы должны сделать 'PostCell' подкласс« MGSwipeTableCell », если вы еще этого не сделали. Я предполагаю, что вы спрашиваете о 'var cell = ...; если cell == nil'. Это альтернативный, менее осторожный способ сказать «if let cell = ...» Однако блоки if и else меняются на противоположные. – beyowulf

+0

Не могли бы вы подробнее рассказать? У меня есть «PostCell» в качестве подкласса «MGSwipeTableCell». И да, я спрашиваю о 'var cell = ...; если cell == nil'. – ryanbilak

ответ

0

if let cell = tableView.dequeueReusableCellWithIdentifier("PostCell") то же самое, как говорят

if tableView.dequeueReusableCellWithIdentifier("PostCell") != nil { 
    let cell = tableView.dequeueReusableCellWithIdentifier("PostCell") 
    } 

Они делают что-то подобное, объявив переменную настройки ее равной необязательная. Они проверяют, является ли опциональным значение nil. Если это так, они инициализируют новый объект и устанавливают ячейку, равную этому, поэтому они могут безопасно разворачиваться.

Если PostCell является подклассом MGSwipeTableCell, вы можете добавить leftButtons и rightButtons так же, как они. например

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 

    let post = posts[indexPath.row] 

    if let cell = tableView.dequeueReusableCellWithIdentifier("PostCell") as? PostCell { 
    cell.request?.cancel() 

    var img: UIImage? 

    if let url = post.imageUrl { 
     img = FeedVCViewController.imageCache.objectForKey(url) as? UIImage 
    } 

    cell.configureCell(post, img: img) 



    cell.rightButtons = [MGSwipeButton(title: "Delete", backgroundColor: UIColor.redColor(), callback: { 
     (sender: MGSwipeTableCell!) -> Bool in 
     print("Convenience callback for delete button!") 
     return true 
    }) 
     ,MGSwipeButton(title: "More",backgroundColor: UIColor.lightGrayColor(),callback: { 
     (sender: MGSwipeTableCell!) -> Bool in 
     print("Convenience callback for more button!") 
     return true 
    })] 

    return cell 
    } else { 
     return PostCell() 
    } 
} 
Смежные вопросы