前言: 學(xué)習(xí)Swift
語法的同時, 加上一點點的小實踐. 囧~
OC版本帶箭頭的View
OC&Swift版本的Demo如果你想看看
- 熟悉swift語法
- Swift中的drawRect
- 擴(kuò)展閱讀
- Swift源碼推薦
- 一如既往的圖文并茂
效果演示f
這里我只做了箭頭在上方中心位置作為演示, 如需要箭頭的位置改變可參照我上面提到的文章.
// 然而我還是定義了一個枚舉, 然而并沒有用 [大笑](就當(dāng)做熟悉一下語法好啦)
enum ArrowOfDirection {
case XTUpCenter
}
構(gòu)造過程
var bgView = UIView()
var origin = CGPoint()
var height = 0.0
var width = 0.0
var arrow = ArrowOfDirection.XTUpCenter
// 初始化方法
required init(origin: CGPoint, width: Double, height: Double) {
super.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.height))
self.backgroundColor = UIColor.clear
self.origin = origin
self.width = Double(width)
self.height = Double(height)
let x = Double(origin.x)
let y = Double(origin.y)
bgView = UIView.init(frame: CGRect.init(x: x, y: y, width: width, height: height))
self.addSubview(self.bgView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
畫出一個箭頭
override func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
let startX = self.origin.x
let startY = self.origin.y
context?.move(to: CGPoint.init(x: startX, y: startY))
// 畫出兩條線
context?.addLine(to: CGPoint.init(x: startX + 5.0, y: startY + 5.0))
context?.addLine(to: CGPoint.init(x: startX - 5.0, y: startY + 5.0))
context?.closePath()
// 填充顏色
self.bgView.backgroundColor?.setFill()
self.backgroundColor?.setStroke()
context?.drawPath(using: CGPathDrawingMode.fillStroke)
}
func popView()->Void{
// 創(chuàng)建keyWindow
let window = UIApplication.shared.keyWindow
window?.addSubview(self)
self.bgView.frame = CGRect.init(x: self.origin.x, y: self.origin.y + 5.0, width: 0, height: 0)
// 類型CGFloat -> Double
let originX = Double(self.origin.x) - self.width / 2
let originY = Double(self.origin.y) + 5.0
let width = self.width
let height = self.height
// 這里為什么抽出一個方法呢, 如果有很多類型箭頭就方便很多, 可以看看OC版本
self.updateFrame(x: originX, y: originY, width: width, height: height)
}
調(diào)整Frame
touchesBegan
這個方法完成點擊除黑色View以外的部分, 移除View操作
func updateFrame(x: Double, y: Double, width: Double, height: Double){
self.bgView.frame = CGRect.init(x: x, y: y, width: width, height: height)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
// 這里遍歷包含UITouch的集合, 從中找到黑色View
for touch: AnyObject in touches {
let t:UITouch = touch as! UITouch
if(!(t.view?.isEqual(self.bgView))!){
self.dismiss()
}
}
}
移除方法 , 順便感受一下Swift GCD 操作
func dismiss()->Void{
let delay = DispatchTime.now() + DispatchTimeInterval.seconds(1)
DispatchQueue.main.asyncAfter(deadline: delay) {
// 延遲執(zhí)行
let res = self.subviews
for view in res {
view.removeFromSuperview()
}
self.removeFromSuperview()
}
}
推薦閱讀 卓同學(xué)的文章
Swift 3必看:從使用場景了解GCD新API
源碼推薦
https://github.com/tristanhimmelman/HidingNavigationBar
介紹
- 隱藏導(dǎo)航欄
- 隱藏導(dǎo)航欄+ Extension View
- 隱藏導(dǎo)航欄+ ToolBar
- 隱藏導(dǎo)航欄+ TabBar
效果演示
如果可以 請給我點個喜歡 0.O
文 / 夏天然后
一個喜歡瞎折騰的偽文藝青年 如果對你有所幫助請點贊/關(guān)注我 摸摸d