我有一个UITextView自定义类:
class TitleTextView: UITextView {
override func layoutSubviews() {
super.layoutSubviews()
setup()
}
func setup() {
textContainerInset = UIEdgeInsets.zero
textContainer.lineFragmentPadding = 0
textColor = .brand100
backgroundColor = .clear
isUserInteractionEnabled = false
textAlignment = .left
isScrollEnabled = false
let frameWidth = Constants.screenSize.width * 87.5 / 100
font = UIFont.OpenSans(.semibold, size: (frameWidth * 8.55 / 100))
}
}
我在UIView中使用了此文本视图自定义类。
class MyCustomHeaderView: UIView{
@IBOutlet weak var titleTextView: TitleTextView!
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func layoutSubviews() {
backgroundColor = .brand100
titleTextView.text = "Market Place"
titleTextView.textColor = .brand400
layoutIfNeeded()
}
}
而且我在UIViewController中将此UIView称为。
private func setupTitleView() {
let titleView = UINib(nibName: "TitleView", bundle: .main).instantiate(withOwner: nil, options: nil).first as! UIView
titleView.frame = contentHeaderView.bounds
contentHeaderView.addSubview(titleView)
view.layoutIfNeeded()
}
但是当我在自定义UIView(MyCustomHeaderView)中设置textColor属性时,颜色不会更改。
您是否知道为什么我的UITextView不应用我在自定义UIView中设置的颜色的原因?我打电话给layoutIfNeed()
,但这不起作用。
这是因为您正在layoutSubviews
内部做所有事情,这实际上是一种不好的做法。
在您的情况下,您实例化了CustomHeaderView
并调用了它的布局,因此调用layoutSubviews
的下一步是将textView
添加到您的CustomHeaderView
中,然后调用textView的layoutSubviews
并会覆盖您的颜色。
我相信您可以通过两种方式解决此问题。我不使用笔尖和情节提要,
第一:
class MyCustomHeaderView: UIView{
@IBOutlet weak var titleTextView: TitleTextView!
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setup() {
backgroundColor = .brand100
titleTextView.text = "Market Place"
titleTextView.textColor = .brand400
layoutIfNeeded()
}
}
第二,这可能很大:
class MyCustomHeaderView: UIView{
@IBOutlet weak var titleTextView: TitleTextView!
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func layoutSubviews() {
defer {
backgroundColor = .brand100
titleTextView.text = "Market Place"
titleTextView.textColor = .brand400
layoutIfNeeded()
}
}
}
延迟将等到所有东西都初始化之后再运行块中的任何内容。我不知道那怎么用layoutSubviews