2016-06-26 35 views
10

Sono 3 giorni nuovo a veloce, e sto cercando di capire come disegnare un rettangolo. Sono troppo nuovo per la lingua per conoscere le classi da estendere ei metodi per scavalcare, e ho cercato il codice di esempio, ma niente sembra funzionare (cosa che sto attribuendo al mio uso di swift 3).Swift 3: disegno di un rettangolo

Quello che sto cercando ora è:

import UIKit 

class ViewController: UIViewController { 

    override func viewDidLoad() { 
     super.viewDidLoad() 


     let k = Draw(frame: CGRect(
      origin: CGPoint(x: 50, y: 50), 
      size: CGSize(width: 100, height: 100))) 

     k.draw(CGRect(
      origin: CGPoint(x: 50, y: 50), 
      size: CGSize(width: 100, height: 100))); 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 


} 
class Draw: 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 h = rect.height 
     let w = rect.width 
     var color:UIColor = UIColor.yellow() 

     var drect = CGRect(x: (w * 0.25),y: (h * 0.25),width: (w * 0.5),height: (h * 0.5)) 
     var bpath:UIBezierPath = UIBezierPath(rect: drect) 

     color.set() 
     bpath.stroke() 

     print("it ran") 

     NSLog("drawRect has updated the view") 

    } 

} 

E che non sta facendo nulla. Aiuto.

+0

Se sei appena agli inizi, fare domande di questo tipo su Stack Overflow non è il posto che devi essere. Dovresti trovare un buon libro o una serie di tutorial online.Dai un'occhiata a [Buone risorse per l'apprendimento di ObjC] (http://stackoverflow.com/q/1374660); include riferimenti per iOS e la maggior parte del materiale sarà stata aggiornata per Swift a questo punto. In bocca al lupo! –

+1

1. Non chiamare mai "disegnare" da soli. 2. Basta chiamare 'view.addSubview (k)' per aggiungere la vista alla propria gerarchia di viste, e il sistema operativo chiamerà il metodo 'draw' per te quando è necessario. – Rob

risposta

11

Per vedere la vista, è necessario crearne una e dargli una cornice in modo che sappia quanto sia grande per realizzarla.

Se mettete il vostro codice in un parco giochi, e quindi aggiungere questa linea:

let d = Draw(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) 

sarete in grado di fare clic sul Quick View a destra, e poi vedrete il vista.

Yellow square in a playground


È inoltre possibile aggiungere la vista come una visualizzazione secondaria di view nella vostra ViewController e poi vedrete che su iPhone:

override func viewDidLoad() { 
    super.viewDidLoad() 

    let k = Draw(frame: CGRect(
     origin: CGPoint(x: 50, y: 50), 
     size: CGSize(width: 100, height: 100))) 

    // Add the view to the view hierarchy so that it shows up on screen 
    self.view.addSubview(k) 
} 

Nota che non si chiami draw(_:) direttamente. Si chiama per Cocoa Touch per visualizzare la vista.

Yellow square on iPhoneSE

7

creare una classe, l'ho messo in un file di Swift 3 separato.

// 
// Plot_Demo.swift 
// 
// Storyboard is not good in creating self adapting UI 
// Plot_Demo creates the drawing programatically. 

import Foundation 
import UIKit 

public class Plot_Demo: UIView 
{ 
    override init(frame: CGRect) { 
     super.init(frame: frame) 
    } 

    required public init?(coder aDecoder: NSCoder) { 
     fatalError("init(coder:) has not been implemented") 
    } 

    public override func draw(_ frame: CGRect) { 
     let h = frame.height 
     let w = frame.width 
     let color:UIColor = UIColor.yellow 

     let drect = CGRect(x: (w * 0.25), y: (h * 0.25), width: (w * 0.5), height: (h * 0.5)) 
     let bpath:UIBezierPath = UIBezierPath(rect: drect) 

     color.set() 
     bpath.stroke() 

     print("it ran") 
     NSLog("drawRect has updated the view") 
    } 
} 

Esempio di utilizzo in un oggetto UIViewController:

override func viewDidLoad() { 
    super.viewDidLoad() 

    // Instantiate a new Plot_Demo object (inherits and has all properties of UIView) 
    let k = Plot_Demo(frame: CGRect(x: 75, y: 75, width: 150, height: 150)) 

    // Put the rectangle in the canvas in this new object 
    k.draw(CGRect(x: 50, y: 50, width: 100, height: 100)) 

    // view: UIView was created earlier using StoryBoard 
    // Display the contents (our rectangle) by attaching it 
    self.view.addSubview(k) 
} 

Run in un simulatore di iPhone e su un iPhone:

enter image description here

Usato XCode versione 8.0 (8A218a), Swift 3, target iOS 10.0

+2

Dalla documentazione 'draw (_ :)': - Non dovresti mai chiamare questo metodo direttamente da solo. Per invalidare parte della vista, e quindi causare che quella parte sia ridisegnata, chiama invece il metodo 'setNeedsDisplay()' o 'setNeedsDisplay (_ :)'. – bshirley

0

Questo è un altro modo di disegno Rettangolo,

Fase 1: Get percorso rettangolo di punti dati

(Nota: arrPathPoints deve essere 4 nella conta per disegnare rettangolo),

func getPathPayer(arrPathPoints:[CGPoint]) throws -> CAShapeLayer { 
     enum PathError : Error{ 
      case moreThan2PointsNeeded 
     } 

     guard arrPathPoints.count > 2 else { 
      throw PathError.moreThan2PointsNeeded 
     } 

     let lineColor = UIColor.blue 
     let lineWidth: CGFloat = 2 
     let path = UIBezierPath() 
     let pathLayer = CAShapeLayer() 

     for (index,pathPoint) in arrPathPoints.enumerated() { 
      switch index { 
      //First point 
      case 0: 
       path.move(to: pathPoint) 

      //Last point 
      case arrPathPoints.count - 1: 
       path.addLine(to: pathPoint) 
       path.close() 

      //Middle Points 
      default: 
       path.addLine(to: pathPoint) 
      } 
     } 

     pathLayer.path = path.cgPath 
     pathLayer.strokeColor = lineColor.cgColor 
     pathLayer.lineWidth = lineWidth 
     pathLayer.fillColor = UIColor.clear.cgColor 

     return pathLayer 
    } 

Fase 2: Utilizzo, metodo di chiamata come questo,

override func viewDidLoad() { 
     super.viewDidLoad() 

     do { 
      let rectangleLayer = try getPathPayer(arrPathPoints: [ 
       CGPoint(x: 110, y: 110), //Top-Left 
       CGPoint(x: 130, y: 110), //Top-Right 
       CGPoint(x: 130, y: 130), //Bottom-Right 
       CGPoint(x: 110, y: 130)]) //Bottom-Left 
      view.layer.addSublayer(rectangleLayer) 
     } catch { 
      debugPrint(error) 
     } 
    }