Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

ios - Possible to get view size from within a class? (Swift)

If a subview of class MyClass is added to another view:

secondView = MyClass() 
mainView.addSubview(secondView)

is it possible to get the subview's dimensions from within the class?

secondView = MyClass()
mainView.addSubview(secondView)

class MyClass: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }
    func commonInit() -> Void {
        // do whatever the view will need to show
        // *** can I get the view's dimensions here? <----------------------***
        // e.g., draw a diagonal line 
        //  from top left corner to bottom right corner

        // self.bounds and self.frame return (0, 0, 0, 0) here
    }
}

Or do they need to be passed in somehow from the view creating it (mainView)?

question from:https://stackoverflow.com/questions/65713480/possible-to-get-view-size-from-within-a-class-swift

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You cannot get a view's size reliably within init. A view's size can change. Therefore you should either do any drawing you need in drawrect, or if you are using CALAyer, resize your layer in layoutSubviews where you will have the bounds of your view and you can then use that to set the frame of your sublayer or subviews. https://developer.apple.com/documentation/uikit/uiview/1622482-layoutsubviews https://developer.apple.com/documentation/uikit/uiview/1622529-drawrect Here is a playground with a simple line example.

import UIKit
import Combine
import PlaygroundSupport

final class XView: UIView {
    override func draw(_ rect: CGRect) {
        super.draw(rect)
        UIColor.red.setStroke()
        let path = UIBezierPath()
        path.lineWidth = 10
        path.move(to: rect.origin)
        path.addLine(to: .init(x: rect.maxX, y: rect.maxY))
        path.stroke()
    }
}
let v = XView()
v.frame = .init(origin: .zero, size: .init(width: 300, height: 300))
PlaygroundPage.current.liveView = XView()

If you want the fancy version see my GitHub project here: https://github.com/joshuajhomann/pathmorpher/tree/master/final


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...