programing

Swift에서 UIView 서브클래스의 커스텀 init을 작성하려면 어떻게 해야 하나요?

magicmemo 2023. 4. 21. 20:27
반응형

Swift에서 UIView 서브클래스의 커스텀 init을 작성하려면 어떻게 해야 하나요?

Say I want toinit a UIView로 하위 분류하다.String그리고Int.

스위프트에서 이걸 어떻게 할 수 있겠어?UIView커스텀을 만들면init()이 함수는 String과 Int입니다.이것은 "super.init()가 이니셜라이저에서 돌아오기 전에 호출되지 않았습니다"라는 것을 나타냅니다.

그리고 내가 전화하면super.init()전용 이니셜라이저를 사용해야 한다고 합니다.저는 거기서 무엇을 사용해야 하나요?프레임 버전?코더 버전?둘 다요? 왜요?

init(frame:)version은 기본 이니셜라이저입니다.인스턴스 변수를 초기화한 후에만 호출해야 합니다.이 뷰를 Nib에서 재구성하는 경우 커스텀 이니셜라이저가 호출되지 않고 대신init?(coder:)버전이 호출됩니다.이제 Swift는 필요한 기능을 구현해야 합니다.init?(coder:)아래 예시를 갱신하여 변경하였습니다.let에 대한 가변var옵션입니다.이 경우는, 다음의 순서로 초기화합니다.awakeFromNib()또는 나중에.

class TestView : UIView {
    var s: String?
    var i: Int?
    init(s: String, i: Int) {
        self.s = s
        self.i = i
        super.init(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

지정 및 필수 항목에 대한 공통 init을 만듭니다.편의를 위해 위임합니다.init(frame:)프레임이 0으로 되어 있습니다.

일반적으로 뷰는 ViewController 뷰 내에 있기 때문에 프레임이 제로인 것은 문제가 되지 않습니다.커스텀 뷰는 슈퍼뷰가 호출될 때 서브뷰를 레이아웃할 수 있습니다.layoutSubviews()또는updateConstraints()이 두 함수는 뷰 계층 전체에서 시스템에 의해 재귀적으로 호출됩니다.둘 중 하나를 사용할 수 있습니다.updateContstraints()또는layoutSubviews().updateContstraints()그러면 먼저 호출됩니다.layoutSubviews()updateConstraints()슈퍼라스트 꼭 불러주세요.layoutSubviews(), super를 먼저 호출합니다.

제가 하는 일은 다음과 같습니다.

@IBDesignable
class MyView: UIView {

      convenience init(args: Whatever) {
          self.init(frame: CGRect.zero)
          //assign custom vars
      }

      override init(frame: CGRect) {
           super.init(frame: frame)
           commonInit()
      }

      required init?(coder aDecoder: NSCoder) {
           super.init(coder: aDecoder)
           commonInit()
      }

      override func prepareForInterfaceBuilder() {
           super.prepareForInterfaceBuilder()
           commonInit()
      }

      private func commonInit() {
           //custom initialization
      }

      override func updateConstraints() {
           //set subview constraints here
           super.updateConstraints()
      }

      override func layoutSubviews() {
           super.layoutSubviews()
           //manually set subview frames here
      }

}

Swift 5 솔루션

XCode 11에서 Swift 5를 실행하기 위해 이 구현을 시험해 볼 수 있습니다.


class CustomView: UIView {

    var customParam: customType
    
    var container = UIView()
    
    required init(customParamArg: customType) {
        self.customParam = customParamArg
        super.init(frame: .zero)
        // Setting up the view can be done here
        setupView()
    }

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

    func setupView() {
        // Can do the setup of the view, including adding subviews

        setupConstraints()
    }
    
    func setupConstraints() {
        // setup custom constraints as you wish
    }
    
    
}


Swift에서 iOS 9를 사용하는 방법은 다음과 같습니다.

import UIKit

class CustomView : UIView {

    init() {
        super.init(frame: UIScreen.mainScreen().bounds);

        //for debug validation
        self.backgroundColor = UIColor.blueColor();
        print("My Custom Init");

        return;
    }

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

다음은 전체 프로젝트와 예시입니다.

Swift에서 iOS 서브뷰를 하는 방법은 다음과 같습니다.

class CustomSubview : UIView {

    init() {
        super.init(frame: UIScreen.mainScreen().bounds);

        let windowHeight : CGFloat = 150;
        let windowWidth  : CGFloat = 360;

        self.backgroundColor = UIColor.whiteColor();
        self.frame = CGRectMake(0, 0, windowWidth, windowHeight);
        self.center = CGPoint(x: UIScreen.mainScreen().bounds.width/2, y: 375);

        //for debug validation
        self.backgroundColor = UIColor.grayColor();
        print("My Custom Init");

        return;
    }

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

언급URL : https://stackoverflow.com/questions/24339145/how-do-i-write-a-custom-init-for-a-uiview-subclass-in-swift

반응형