2017-05-07 104 views
0

我有一个视图,我用作tableView中的标题。视图非常简单,它只有内部标签。如果我在其中定义一个带有字符串赋值的自定义init,则不起作用。UIView与自定义init不起作用

的代码如下

class ProducutDetailsTableViewHeader: UIView { 

var sectionTitle: UILabel = { 
    var label = UILabel() 
    label.textAlignment = .left 
    label.font = UIFont(name: "Lato-Regular", size: 13) 
    label.textColor = UIColor.init(red: 107/255, green: 107/255, blue: 118/255, alpha: 1.0) 
    label.translatesAutoresizingMaskIntoConstraints = false 
    label.numberOfLines = 0 
    label.translatesAutoresizingMaskIntoConstraints = false 
    return label 
}() 

override init(frame: CGRect) { 
    super.init(frame: frame) 
    addSubview(sectionTitle) 

    sectionTitle.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 24).isActive = true 
    sectionTitle.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true 

    backgroundColor = UIColor.init(red: 242/255, green: 242/255, blue: 244/255, alpha: 1.0) 

} 

required init?(coder aDecoder: NSCoder) { 
    fatalError("init(coder:) has not been implemented") 
} 

init(text: String) { 
    sectionTitle.text = text 
    super.init(frame: .zero) 
} 
} 

如果我使用下面的代码,我没有得到我的头可见

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { 
    if section == 0 { 
     return ProducutDetailsTableViewHeader(text: "PREVED") 
    } 
    return nil 
} 

但有了这个代码,一切正常

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { 
    if section == 0 { 
     let view = ProducutDetailsTableViewHeader() 
     view.sectionTitle.text = "Preved" 
     return view 
    } 
    return nil 
} 

看起来我对inits做错了什么。究竟是什么?

回答

4

试着改变你的init(text: String)方法,看看,如果这个工程:

convenience init(text: String) { 
    self.init(frame: .zero) 
    sectionTitle.text = text 
} 

,当你调用super.init您所呼叫的UIViewController的默认init方法,而不是你的 init方法。通过调用self.init,确保您正在调用正确的方法。

+0

因此'self.init'调用这一行'override init(frame:CGRect)'...最终调用'super.init'的权利? – Honey

+0

是的,正确的,super.init调用父类,自我调用你所指的那个。 – Scriptable

0

如果你用nib使用自定义视图,那么就不需要单独给出'init'方法。

在这种情况下,需要使用以下来加载从束视图,

让subViewArray = Bundle.main.loadNibNamed( “NibName”,拥有者:自,选项:无) 让子视图= subViewArray [0 ]

如果你将使用init方法,你的视图的内容将为零。 让我知道你是否有更多的疑问。