New Swift object

I have been writing code for apps that provide visual representations of conditions. Imagine a bouncing ball. To do do this, I have been using the Color Well object because it allows me to control size, location, and color. However, even without a border, a slight outline is present. And, the shape is always a square.

Is there a third-party extension to Swift that includes an object with controllable size, location, and color?

I'm using Xcode 8.3.3. I think that that corresponds to Swift 3.

Thanks.

You are on Cocoa? If so, the solution is quite simple.

Color

class ControllableView: NSView {
    override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)
        
        // For a red color
        let path = NSBezierPath(rect: bounds)
        NSColor.red.setFill()
        path.fill()
    }
}

In your storyboard, change the view type to ControllableView.

Movement/Size
In NSViewController, you can simply use the .frame settable property to move around and resize your view.

Sorry about putting this in another post (I should have read your question more clearly):

You can use various methods on NSBezierPath to change shapes. This class allows you to draw lines, circles, etc. See https://developer.apple.com/documentation/appkit/nsbezierpath.

Yes, Cocoa. The information you provided is better than I expected. Thanks!

I spoke too soon. How can I change the object's color dynamically?

class ControllableView: NSView {
   var redIndex = CGFloat(0.0/255.0)
   var greenIndex = CGFloat(0.0/255.0)
   var blueIndex = CGFloat(0.0/255.0)

   override func draw(_ dirtyRect: NSRect) {
       super.draw(dirtyRect)
    
       let path = NSBezierPath(ovalIn: bounds)
       NSColor(red: redIndex, green: greenIndex, blue: blueIndex, alpha: 1).setFill()
       path.fill()
   }
}

That works as long as you pair every change to the color with a call to setNeedsDisplay.

Terms of Service

Privacy Policy

Cookie Policy