我正在尝试为项目中的所有 ViewControllers 创建自定义头文件。下图是实际设计。
因此,我尝试使用Xib文件创建自定义视图,如下所示:
import UIKit
class HamburgrView: UIView {
override init(frame: CGRect) {
// 1. setup any properties here
// 2. call super.init(frame:)
super.init(frame: frame)
// 3. Setup view from .xib file
xibSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
}
override open func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
xibSetup()
}
override func layoutSubviews() {
}
func xibSetup() {
let tempView = loadViewFromNib()
// use bounds not frame or it'll be offset
tempView.frame = bounds
// Make the view stretch with containing view
tempView.autoresizingMask = [.flexibleWidth,.flexibleHeight]
// Adding custom subview on top of our view (over any custom drawing > see note below)
addSubview(tempView)
}
func loadViewFromNib() -> UIView {
let bundle = Bundle(for: type(of:self))
let nib = UINib(nibName: "HamburgrView",bundle: bundle)
// Assumes UIView is top level and only object in CustomView.xib file
let view = nib.instantiate(withOwner: self,options: nil)[0] as! UIView
return view
}
}
我们不知道如何从 SafeArealayoutGuide 绘制带有曲线及其起始位置的汉堡菜单图标。
我尝试使用x位置为负-40的一个视图,并且使cornerRadius不能像上面的图像那样变得完美。
输出效果不好。
我的 ViewController 代码:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let hamView = HamburgrView(frame: .zero)
self.view.addSubview(hamView)
hamView.translatesAutoresizingMaskintoConstraints = false
NSLayoutConstraint.activate([
hamView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor,constant: 0),hamView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor,hamView.widthAnchor.constraint(equalToConstant: 120),hamView.heightAnchor.constraint(equalToConstant: 80)
])
}
作为@sandip答案,我已经进行了如下更改:
func xibSetup() {
let tempView = loadViewFromNib()
// use bounds not frame or it'll be offset
tempView.frame = bounds
// Make the view stretch with containing view
tempView.autoresizingMask = [.flexibleWidth,.flexibleHeight]
// Adding custom subview on top of our view (over any custom drawing > see note below)
addSubview(tempView)
let layer = CAShapelayer()
layer.path = UIBezierPath.init(arcCenter: CGPoint(x: 0,y: self.center.y),radius: 50,startAngle: -1.5708,endAngle: 1.5708,clockwise: true).cgPath
layer.fillColor = UIColor.red.cgColor
self.layer.addSublayer(layer)
}
输出看起来如下: