【发布时间】:2019-09-12 23:35:42
【问题描述】:
我有这个 UIView 的子类,它创建了一个 UILabel 对象并将其添加为子视图。代码如下。我在视图控制器的视图上放置了一个 UIView 对象,并将子类设置为我的子类 UTIDropDownView。当我在设备上运行应用程序时,我能够看到我绘制的线条,但我没有看到 UILabel 对象。
谁能告诉我我做错了什么?
import UIKit
class UTIDropDownView: UIView {
var label = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
let labelFrame = CGRect(width: frame.width - frame.height, height: frame.height)
label = UILabel(frame: labelFrame)
addSubview(label)
label.text = "UTIDropDownView"
label.isHidden = false
label.isUserInteractionEnabled = true
label.backgroundColor = UIColor.red
label.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint(item: label, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: label, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: frame.height).isActive = true
NSLayoutConstraint(item: label, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: label, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0).isActive = true
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
let labelWidth: CGFloat = frame.width - frame.height
let triangleBorder: CGFloat = frame.height * 0.1
let path = UIBezierPath()
UIColor.darkGray.setStroke()
path.move(to: CGPoint(x: labelWidth + triangleBorder, y: triangleBorder))
path.addLine(to: CGPoint(x: frame.width - triangleBorder, y: triangleBorder))
path.stroke()
}
}
当我在 draw(_:) 中添加以下代码时
print(rect)
我得到以下打印结果:
(0.0, 0.0, 120.0, 30.0)
【问题讨论】:
-
使用 View Hierarchy 调试器转储视图层次结构并查看标签的位置。也许出于某种原因它在屏幕外的某个地方?
-
你能检查一下你初始化视图的尺寸吗?根据您对标签的尺寸计算,宽度可能低于 0。
-
@Rudedog 我不知道如何使用 View Hierarchy 调试器转储视图层次结构。你是怎样做的?宽度为 120,高度为 30,我在 Interface Builder 中设置。
-
当你使用界面生成器时,init() 不会被调用,只有
init?(coder:) -
你可以做的是将配置和添加标签的代码放在一个单独的方法中,并从
init(frame:)和init?(coder:)调用该方法,这样你就可以确定代码被执行了.
标签: ios swift uiview uilabel subview