Swift tableView тип набора аксессуаров

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    @IBOutlet
    var tableView: UITableView
    var items: String[] = ["We", "Heart", "Swift"]

    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "myCell")
    }


    func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
        return self.items.count;
    }

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

        var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("myCell") as UITableViewCell

        cell.textLabel.text = self.items[indexPath.row]
        cell.accessoryType = UITableViewCellAccessoryType.DetailDisclosureButton
        cell.selectionStyle = UITableViewCellSelectionStyle.Blue
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        return cell
    }

    func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
        println("You selected cell #\(indexPath.row)!")

    }
}

Моя проблема в том, что атрибут accessoriesType и selectionStyle не изменяются. Изменяется tableView.separatorStyle, а также cell.textlabel.text. Как я могу это исправить?

Ответы

Ответ 1

UITableViewCell.SelectionStyle.blue

При выделении ячейка имеет цвет фона по умолчанию.

В iOS 7 цвет выбора больше не синий. Вместо этого используйте UITableViewCell.SelectionStyle.default.

Что касается accessoryType, он должен работать нормально, если вы не измените его позже где-нибудь еще. Убедитесь, что ширина таблицы правильная, иначе вспомогательные виды могут быть вне экрана.

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet
    var tableView: UITableView

    var items: String[] = ["We", "Heart", "Swift"]

    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "myCell")
    }


    func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
        return self.items.count;
    }

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

        var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("myCell") as UITableViewCell
        cell.textLabel.text = self.items[indexPath.row]
        cell.selectionStyle = UITableView.CellSelectionStyle.blue

        /*
        enum UITableViewCellAccessoryType : Int {
        case none // don't show any accessory view
        case disclosureIndicator // regular chevron. doesn't track
        case detailDisclosureButton // info button w/ chevron. tracks
        case checkmark // checkmark. doesn't track
        case detailButton // info button. tracks
        }
        */

        // Standard options
        cell.accessoryType = UITableViewCell.AccessoryType.none
        cell.accessoryType = UITableViewCell.AccessoryType.disclosureIndicator
        cell.accessoryType = UITableViewCell.AccessoryType.detailDisclosureButton
        cell.accessoryType = UITableViewCell.AccessoryType.checkmark
        cell.accessoryType = UITableViewCell.AccessoryType.detailButton

        // Custom view options
        cell.accessoryType = UITableViewCell.AccessoryType.none
        cell.accessoryView = UIView(frame: CGRectMake(0, 0, 20, 20))
        cell.accessoryView.backgroundColor = UIColor.blueColor()

        return cell
    }

    func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
        println("You selected cell #\(indexPath.row)!")

    }
}

Обратите внимание, что не рекомендуется устанавливать separatorStyle таблицы каждый раз, когда запрашивается ячейка, а делать это один раз при tableView: at viewDidLoad.

Ответ 2

Мне не удавалось установить его в методе cellForRowAtIndexPath, переместив его на willDisplayCell, исправив проблему, пока она не появилась.

override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    cell.accessoryType = .DisclosureIndicator
}

Ответ 3

Я хотел бы поделиться своим опытом об этом, у меня была та же проблема, cell.accessoryType = IUTableViewCellAccessoryType.Checkmark И я заметил, что у моего табличного представления не было ограничений, поэтому я добавил недостающие ограничения, после чего он работал у меня.