I very rarely override drawRect in my UIView subclasses, usually preferring to set layer.contents
with pre-rendering images and often employing multiple sublayers or subviews and manipulating these based on input parameters. Is there a way for IB to render these more complex view stacks?
相关问题
- CALayer - backgroundColor flipped?
- Core Data lightweight migration crashes after App
- “Zero out” sensitive String data in Swift
- back button text does not change
- SwiftUI: UIImage (QRCode) does not load after call
相关文章
- 现在使用swift开发ios应用好还是swift?
- Using if let syntax in switch statement
- TCC __TCCAccessRequest_block_invoke
- xcode 4 garbage collection removed?
- Xcode: Is there a way to change line spacing (UI L
- Unable to process app at this time due to a genera
- Enum with associated value conforming to CaseItera
- Swift - hide pickerView after value selected
I think layoutSubviews is the simplest mechanism.
Here is a (much) simpler example in Swift:
I haven't tested this snippet, but have used patterns like this before. Note the use of the lazy property delegating to a computed property to simplify initial configuration.
I believe you can implement
prepareForInterfaceBuilder
and do your core animation work in there to get it to show up in IB. I've done some fancy things with subclasses of UIButton that do their own core animation layer work to draw borders or backgrounds, and they live render in interface builder just fine, so i imagine if you're subclassing UIView directly, thenprepareForInterfaceBuilder
is all you'll need to do differently. Keep in mind though that the method is only ever executed by IBEdited to include code as requested
I have something similar to, but not exactly like this (sorry I can't give you what I really do, but it's a work thing)
I override both
initWithCoder
andinitWithFrame
because I want to be able to use the component in code or in IB (and as other answers state, you have to implementinitWithFrame
to make IB happy.Then in
commonInit
I set up the core animation stuff to draw a border and make it pretty.I also implement a
willSet
for the highlighted variable to change the background color because I hate when buttons draw borders, but don't provide feedback when pressed (i hate it when the pressed button looks like the unpressed button)