Ios UITextView不更改textColor属性
我有一个UITextView自定义类:Ios UITextView不更改textColor属性,ios,swift,swift4,uitextview,Ios,Swift,Swift4,Uitextview,我有一个UITextView自定义类: class TitleTextView: UITextView { override func layoutSubviews() { super.layoutSubviews() setup() } func setup() { textContainerInset = UIEdgeInsets.zero textContainer.lineFragmentPadd
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中设置的颜色吗?
我调用了
layoutfneed()
,但这不起作用。这是因为您在layoutSubview
中执行所有操作,这本身就是一种非常糟糕的做法
在您的例子中,实例化CustomHeaderView
并调用其布局,因此调用LayoutSubview
下一步是将textView
添加到CustomHeaderView
中,然后调用textView的LayoutSubview
,并覆盖您的颜色
我相信有两种方法可以解决这个问题。虽然我不使用笔尖和故事板
第一:
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()
}
}
}
在运行块中的任何内容之前,延迟将一直等到所有内容都已初始化。我不知道如何处理LayoutSubview,我认为在这一行中,``let titleView=UINib(nibName:“titleView”,bundle:.main)。实例化(所有者:nil,选项:nil)。首先是!UIView``您应该将类型从UIView更改为所需的自定义类