我有一个 UIView
,它是我在 xib 文件中创建并集成到我的 Storyboard 中的。此 View 就像一个选项卡,您可以拖动它来显示它。
我想在顶部边缘添加一个小矩形,这样当我的 UIView
隐藏时,只有小矩形可见,我可以拉动我的 UIView
通过拖动这个小矩形。
为此,我重写了 UIView
drawRect
方法
override func drawRect(rect: CGRect) {
super.drawRect(rect)
let context = UIGraphicsGetCurrentContext()
CGContextSetFillColorWithColor(context, UIColor.purpleColor().CGColor)
CGContextMoveToPoint(context, rect.width / 2 - 20, 0)
CGContextAddLineToPoint(context, rect.width / 2 - 20, -20)
CGContextAddLineToPoint(context, rect.width / 2 + 20, -20)
CGContextAddLineToPoint(context, rect.width / 2 + 20, 0)
CGContextFillPath(context)
}
当我运行它时,我什么也看不到,甚至在 View 层次结构中也看不到...
我做错了什么吗?
最佳答案
您拖动的矩形必须在 View (或单独的 View )内,因为落在其父 View 边界之外的 View 不会接收到触摸。我这样做的方法是使用 CAShapeLayer 作为 View 的 mask ,让它从 View 顶部开始 20 点,然后在宽度减去 20 的一半处上升到 View 顶部,等等。你会给 View 一个背景颜色,但它只会显示 mask 所在的位置,在其他地方,它将是透明的。在这种情况下,您可以放置 View ,使前 20 个点位于屏幕底部,其余点位于屏幕下方。只有 mask 贴在 View 顶部的矩形才会显示颜色。这是 View 类的代码,
class RDPullTabView: UIView {
let upSwiper = UISwipeGestureRecognizer()
let downSwiper = UISwipeGestureRecognizer()
let shapeLayer = CAShapeLayer()
let bez = UIBezierPath()
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.backgroundColor = UIColor.purpleColor()
self.layer.mask = shapeLayer
upSwiper.direction = .Up
downSwiper.direction = .Down
self.addGestureRecognizer(upSwiper)
self.addGestureRecognizer(downSwiper)
}
override func layoutSubviews() {
super.layoutSubviews()
bez.moveToPoint(CGPoint(x: 0, y: 20))
bez.addLineToPoint(CGPoint(x: self.bounds.size.width/2 - 20, y: 20))
bez.addLineToPoint(CGPoint(x: self.bounds.size.width/2 - 20, y: 0))
bez.addLineToPoint(CGPoint(x: self.bounds.size.width/2 + 20, y: 0))
bez.addLineToPoint(CGPoint(x: self.bounds.size.width/2 + 20, y: 20))
bez.addLineToPoint(CGPoint(x: self.bounds.size.width, y: 20))
bez.addLineToPoint(CGPoint(x: self.bounds.size.width, y: self.bounds.size.height))
bez.addLineToPoint(CGPoint(x: 0, y: self.bounds.size.height))
bez.closePath()
shapeLayer.path = bez.CGPath
}
}
我做了一个约束,从这个view的顶部到controller的self.view的底部,常数为20,controller中的代码是这样的,
class ViewController: UIViewController {
@IBOutlet weak var pullTabView: RDPullTabView!
@IBOutlet weak var bottomCon: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
pullTabView.upSwiper.addTarget(self, action: "handleSwipe:")
pullTabView.downSwiper.addTarget(self, action: "handleSwipe:")
}
func handleSwipe(swiper: UISwipeGestureRecognizer) {
var point = swiper.locationInView(swiper.view)
if pullTabView.bez.containsPoint(point) {
if swiper.direction == UISwipeGestureRecognizerDirection.Up {
bottomCon.constant = 200 // 200 is the height of the pullTabView
}else{
bottomCon.constant = 20;
}
UIView.animateWithDuration(0.3){ self.view.layoutIfNeeded()}
}
}
}
关于ios - 在我的 UIView 的顶部边缘添加一个矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30563751/