我正在學習如何創建自定義UIViews的過程。我正在製作的這個特定視圖包含一對夫婦按鈕。我注意到當我從lazy實例化塊中調用frame/height屬性時,我得到的值是128,但是當我在drawRect函數中傳遞的rect參數上調用height屬性以及邊界時,我得到值94。UIView邊界/框架與drawRect不匹配
我不明白爲什麼從drawRect函數調用的邊界/框架寬度/高度屬性與初始值設定項中使用的框架/邊界高度和寬度不匹配。有人可以解釋這個嗎?
@IBDesignable
class GroupingMetaDataView: UIView {
@IBInspectable var strokeColor: UIColor =
UIColor.blackColor().colorWithAlphaComponent(0.4)
@IBInspectable var strokeWidth: CGFloat = 2.0
lazy var subButton: AddButton! = {
print("frame height: \(self.frame.height)")
print("bounds height: \(self.bounds.height)")
let width = self.frame.width * 0.087
let size = CGSize(width: width, height: width)
let frame = CGRect(origin: CGPoint(x: self.frame.width * 0.055,
y: self.frame.height * 0.5), size: size)
let button = AddButton(frame: frame, isAddButton: false)
return button
}()
lazy var addButton: AddButton! = {
let width = self.frame.width * 0.087
let size = CGSize(width: width, height: width)
let frame = CGRect(origin: CGPoint(x: self.frame.width * 0.857,
y: self.frame.height), size: size)
let button = AddButton(frame: frame, isAddButton: true)
return button
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.setupUI()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setupUI()
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
print("rect height: \(rect.height)")
print("boundsheight: \(bounds.height)")
let context = UIGraphicsGetCurrentContext()
CGContextSetLineWidth(context, strokeWidth)
strokeColor.setStroke()
let topBarPath = UIBezierPath()
topBarPath.moveToPoint(CGPoint(x: 0.0, y: 2.0))
topBarPath.addLineToPoint(CGPoint(x: rect.width, y: 2.0))
topBarPath.lineWidth = strokeWidth
topBarPath.stroke()
let bottomBarPath = UIBezierPath()
bottomBarPath.moveToPoint(CGPoint(x: 0.0, y: rect.height-2.0))
bottomBarPath.addLineToPoint(CGPoint(x: rect.width, y: rect.height-2.0))
bottomBarPath.lineWidth = strokeWidth
bottomBarPath.stroke()
}
// MARK: Setup
func setupUI() {
self.backgroundColor = UIColor.yellowColor()
addSubview(subButton)
addSubview(addButton)
}
}
編輯:
我創建從視圖控制器的GroupingMetaDataView。 YardageMetaDataView是GroupingMetaDataView的一個子類。 YardageMetaDataView不執行任何自定義繪圖。
我注意到了的drawRect參數的文檔指出
需要的視圖的邊界的部分進行更新。第一個 時間您的視圖繪製,這個矩形通常是整個 視圖的可見邊界。但是,在隨後的繪製 操作中,矩形可能只指定部分視圖。
何時以及爲什麼參數rect僅指定視圖的一部分?在觸發setNeedsDisplay之後,drawRect在下一個繪製週期被調用。 SetNeedsDisplay不接受任何參數,所以我假設參數代表整個視圖?
ViewController.swift
class ViewController: UIViewController {
// MARK: - Properties
lazy var yMetaDataView: YardageMetaDataView! = {
let view = YardageMetaDataView(frame: CGRect(origin: CGPoint(x: 50, y: 100),
size: CGSize(width: self.view.bounds.width * 0.75,
height: self.view.bounds.height * 0.102)))
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
}
代碼在哪裏添加到父視圖? – nhgrif
@nhgrif我剛剛添加了實例化視圖的代碼。 – gofly