更改子类中的子视图类

时间:2015-09-16 05:40:44

标签: ios swift subclassing

假设我有一个名为自定义视图的UITableViewCell类,其中包含GenericButton类的按钮,该按钮已通过编程方式在自动布局中定义

class View: UITableViewCell {
    var button: GenericButton

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        button = GenericButton()
        // blah blah blah constraints
    }
}

现在让我说我有一个名为OtherView的View子类,我希望该按钮成为GenericButton的一个子类,名为CircleButton。

class OtherView: View {
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        button = CircleButton()
    }
}

但是,我的视图仍然显示GenericButton,而不是CircleButton。我做错了什么?

2 个答案:

答案 0 :(得分:0)

好的,我已经考虑了好几个小时了,得出的结论是这可能是最好的答案。

import UIKit

class View: UITableViewCell
{
    var button: GenericButton! = nil

    required init(coder aDecoder: NSCoder)
    {
        super.init(coder: aDecoder)
    }

    override init(style: UITableViewCellStyle, reuseIdentifier: String?)
    {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
    }

    convenience init(button: Bool, style: UITableViewCellStyle, reuseIdentifier: String?)
    {
        self.init(style: style, reuseIdentifier: reuseIdentifier)

        if button
        {
            button = GenericButton()
            setConstraint()
        }
    }

    private func setConstraint()
    {
        // blah blah blah constraints
    }
}

class OtherView: View
{
    required init(coder aDecoder: NSCoder)
    {
        super.init(coder: aDecoder)
    }

    override init(style: UITableViewCellStyle, reuseIdentifier: String?)
    {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
    }

    convenience init(button: Bool, style: UITableViewCellStyle, reuseIdentifier: String?)
    {
        self.init(style: buttonWithStyle, reuseIdentifier: reuseIdentifier)

        if button
        {
            button = CircleButton()
            setConstraint()
        }
    }
}

答案 1 :(得分:-1)

我猜你在View的视图层次结构中添加了按钮。如果是这样,button = CircleButton()毫无意义。但是,您仍然可以通过OtherView中的删除按钮执行此操作,然后重新添加。

class View: UITableViewCell {
    var button: GenericButton

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        button = GenericButton()
        addButton(button)
    }

    func addButton(button: UIButton) {
        // add button into view hierarchy here
    }
}

class OtherView: View {
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        button.removeFromSuperview()
        button = CircleButton()
        addButton(button)
    }
}
相关问题