2016-03-31 99 views
0

我有一个自定义UIView子类,我想添加作为我的UIViewController子视图。问题是,即使所有设置都正确(在viewDidLoad视图具有正确的框架,而不是hidden),并且它在Interface Builder(picture)中显示,但运行该应用程序时仍未显示视图。在设备上,我只看到一个红色的屏幕,中间没有三角形。iOS - 自定义UIView不显示在设备上

这里的视图子类:

@IBDesignable 
class TriangleView: UIView { 

    override func drawRect(rect: CGRect) { 
     super.drawRect(rect) 

     let path = UIBezierPath() 
     let width = rect.size.width 
     let height = rect.size.height 
     let startingPoint = CGPoint(x: center.x, y: center.y - height/2) 

     path.moveToPoint(startingPoint) 
     path.addLineToPoint(CGPoint(x: center.x + width/2, y: center.y - height/2)) 
     path.addLineToPoint(CGPoint(x: center.x, y: center.y + height/2)) 
     path.addLineToPoint(CGPoint(x: center.x - width/2, y: center.y - height/2)) 
     path.closePath() 

     let shapeLayer = CAShapeLayer() 
     shapeLayer.frame = rect 
     shapeLayer.position = center 
     shapeLayer.path = path.CGPath 
     shapeLayer.fillColor = UIColor.whiteColor().CGColor 

     layer.mask = shapeLayer 

     layer.backgroundColor = UIColor.redColor().CGColor 
    } 
} 

我没有任何其他的代码显示,我只是认为添加到ViewController并设置其约束和类TriangleView

+0

如果你设置一个断点您的自定义视图的drawRect,将它的调试器停止? – heximal

+0

是的,一切都按原样运作,它只是不显示。忘了提及,在代码中添加视图也不起作用。 – smeshko

+0

您是否尝试过使用Xcode中的Debug View Hierarchy特性来检查运行时的视图? – heximal

回答

3

斯威夫特3

我的工作简化了,你有什么。我知道这是旧的,但这里有一些作品,我相信实现你试图做:

@IBDesignable 
class TriangleView: UIView { 

    override func draw(_ rect: CGRect) { 
     super.draw(rect) 

     let width = rect.size.width 
     let height = rect.size.height 

     let path = UIBezierPath() 
     path.move(to: CGPoint(x: 0, y: 0)) 
     path.addLine(to: CGPoint(x: width, y: 0)) 
     path.addLine(to: CGPoint(x: width/2, y: height)) 
     path.close() 
     path.stroke() 

     let shapeLayer = CAShapeLayer() 
     shapeLayer.fillColor = UIColor.white.cgColor 
     shapeLayer.path = path.cgPath 

     layer.addSublayer(shapeLayer) 
     layer.backgroundColor = UIColor.red.cgColor 
    } 
} 

一些差异:

  • 我只用3分而不是4对三角形然后关闭它。

  • 前2点是在UIView的角落。

  • 我加了layer.addSublayer(shapeLayer)。我相信这就是为什么它在运行应用程序时没有显示出来。

  • 删除了一些我认为不需要的代码,但如果您确实需要,可以将其添加回去。

Simulator

0

你有没有试过,

[self.view bringSubviewToFront:TriangleView] 

加入您的TriangleView为您的视图控制器的子视图后,将这个。

+0

不起作用,已经尝试过。 – smeshko

+0

尝试设置self.view.backgroundColor = [UIColor clearColor];在viewDidLoad中 –

相关问题