Then open the Identity Inspector and associate this view with the custom class (i.e. Then in the main storyboard, select the view, like this: Let context = UIGraphicsGetCurrentContext()Ĭontext?.setStrokeColor()Ĭontext?.addLine(to: CGPoint(x: 20, y: 30))Ĭontext?.setStrokeColor()Ĭontext?.addLine (to: CGPoint(x: 40, y: 45))Ĭontext?.setStrokeColor()Ĭontext?.addLine (to: CGPoint(x: 35, y: 45)) Each class overrides the draw() function in the base UIView class: import UIKit The code contains three classes to write graphics on the view, button and label. I also created a new file in the project, of type Swift, and called it ExampleDraw.swift and put the following code in it. It's possible to draw graphics on Button and Label controls (and the other types of UI controls) because UIButton and UILabel are subclasses of UIView. My example looks like this, where the white square is the View (actually a sub-view because the main screen is also a view): If you try doing that, the code will compile but when it runs, the call to get the graphics context will fail and the calls to the following graphics functions, such as context?.move(), will not run because the context is nil.Īs an example, let's create a storyboard with a View, a Button and a Label by dragging the respective objects from the Object Library onto the storyboard. The 'wrong' place to put the code is in a class that is not a subclass of UIView. It's actually a good question because if you put any of the graphics code in the 'wrong' place, nothing at all will be drawn. The questioner isn't really asking what code to use, he is asking where to put the code.
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |