自定义表视图行动作(图像)

时间:2015-08-25 14:09:18

标签: ios swift cocoa-touch uitableviewrowaction

我的应用包含一个UITableView。它的单元格可以选择显示多行。单元格还具有自定义行动作(图像)。我将行动图像设置为:

let date = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "", handler: { (action, indexPath) -> Void in})    
date.backgroundColor = UIColor(patternImage: UIImage(named: "rowActionPic")!)

图像的分辨率为122x94。如果单元格显示一行,则完全适合。如果单元格显示2行或更多行,则图像将显示2次。有中心图像的选项吗?

cellForRowAtIndexPath中的代码:

cell.textLabel?.numberOfLines = 0
let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject
cell.textLabel?.text = object.valueForKey("name") as? String

1 个答案:

答案 0 :(得分:3)

自然会重复一个模式来填补所有空间。

我成像的唯一方法是增加图像的高度,使其超过最可能的最大像元高度。

我使用了这段代码和一个透明背景和高度为120px的图像,其中图标占据了第一个44x44像素

import UIKit

class ViewController: UITableViewController {
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 30
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
        cell.textLabel?.text = "\(indexPath.row)"
        return cell
    }

    override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? {

        let moreClosure = { (action: UITableViewRowAction!, indexPath: NSIndexPath!) -> Void in
            println("More closure called")
        }

        let moreAction = UITableViewRowAction(style: .Normal, title: "  ", handler: moreClosure)

        if let image = UIImage(named: "star.png"){
            moreAction.backgroundColor = UIColor(patternImage: image)

        }
        return [moreAction]
    }


    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    }


    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
            return  min((44.0 * CGFloat(indexPath.row) + 1), 120.0)
    }
}

结果:

enter image description here

enter image description here

对于具有不透明背景的图像,它看起来更好。

enter image description here

访问GitHub获取示例项目。