我有UIView类在视图上显示行:
import UIKit
class DrawLines: UIView
{
override init(frame: CGRect)
{
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder)
{
fatalError("init(coder:) has not been implemented")
}
override func draw( _ rect: CGRect)
{
let context = UIGraphicsGetCurrentContext()
context!.setLineWidth(2.0)
context!.setStrokeColor(UIColor.white.cgColor)
//make and invisible path first then we fill it in
context!.move(to: CGPoint(x: 0, y: 0))
context!.addLine(to: CGPoint(x: self.bounds.width, y:self.bounds.height))
context!.strokePath()
}
}
主要课程称之为......
import UIKit
class GraphViewController: UIViewController
{
@IBOutlet weak var graphView: UIView!
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let draw = DrawLines(frame: self.graphView.bounds)
view.addSubview(draw)
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
if UIDevice.current.orientation.isLandscape
{
print("landscape")
}
else
{
print("portrait")
}
}
}
但是,旋转屏幕时出现问题。据我所知,问题是 - 它总是使用屏幕的高度和宽度,所以我应该检查横向和放置:
let yLandscaped = self.bounds.width
let xLandscaped = self.bounds.height
但我不知道,如何清除视图内的所有行?
答案 0 :(得分:0)
当我试图旋转时 - 我理解它需要先前的视图边界。所以我颠倒了X和Y的起源。但是当你首先加载它时它应该只是view.bounds。然而,我试图削减图像-10及其下方的高度,应该有一个空的空间,但在它被转动之前有一部分相同的图像!要修复它,只需要输入
while let subview = self.view.subviews.last
{ subview.removeFromSuperview() }
每次轮换前。效果很棒!
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let draw = DrawLines(frame: self.view.bounds)
view.addSubview(draw)
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
if UIDevice.current.orientation.isLandscape
{
print("landscape")
while let subview = self.view.subviews.last
{ subview.removeFromSuperview() }
let draw = DrawLines(frame: CGRect(x: self.view.bounds.origin.y, y: self.view.bounds.origin.x, width: self.view.bounds.height, height: self.view.bounds.width))
view.addSubview(draw)
}
else
{
print("portrait")
while let subview = self.view.subviews.last
{ subview.removeFromSuperview() }
let draw = DrawLines(frame: CGRect(x: self.view.bounds.origin.y, y: self.view.bounds.origin.x, width: self.view.bounds.height, height: self.view.bounds.width))
view.addSubview(draw)
}
}