Пользовательский пользовательский интерфейс; делать что-то, когда размер представления ниже определенного уровня удержания в мусоре

#swift #uiview #size #swift5

#swift #uiview #размер #swift5

Вопрос:

У меня есть пользовательский вид, который я динамически добавляю к другому виду (изображение), который находится в scrollview. Поэтому размер изображения будет варьироваться в зависимости от (начального) масштаба ScrollView. Итак, в основном я хочу установить некоторые свойства и ограничения, когда этот вид был добавлен в представление (изображение). Я думал, что это можно обработать с помощью didMoveToSuperview(), но рамка и границы всегда равны 0??

Как это решить?

Мой пользовательский вид:

 //MARK: - Properties
    private var annotation: Annotation!
    
    private var pinImageView = UIImageView()
    private var completedImageView = UIImageView()
    private var arrowImageView = UIImageView()
    private var pinTitleLabel = ProjectTitleLabel(withTextAlignment: .center, andFont: UIFont.preferredFont(forTextStyle: .callout), andColor: .label)
    
    //MARK: - Init
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required convenience init(with annotation: Annotation) {
        self.init(frame: .zero)
        self.annotation = annotation
        configure()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    //MARK: - Configure view
    private func configure() {
        (...)
    }
    
    override func didMoveToSuperview() {
        print("HERE: (self.frame.height)", bounds.height, intrinsicContentSize)
        //Compensate for when the pin view becomes really small (on very low res images)
        if self.bounds.height <= 40 {
            pinTitleLabel.minimumScaleFactor = 0.45
            pinTitleLabel.font = UIFont.preferredFont(forTextStyle: .caption1)
            pinTitleLabel.heightAnchor.constraint(equalToConstant: 12).isActive = true
            print("SMALL")
        } else {
            pinTitleLabel.heightAnchor.constraint(equalToConstant: 20).isActive = true
            print("NORMAL")
        }
    }
}
  

и код, который добавляет это представление:

     var annotation: Annotation? {
        didSet {
            //remove any previous pin
            mapImageLocationPin?.removeFromSuperview()

            if let location = annotation?.location {
                //Activate the corresponding Map Image and update picker
                selectedMapImage = location.map
                mapImagePickerView.selectRow(mapImagesController.getRowFor(location.map), inComponent: 0, animated: true)

                //Instantiate new Pin with annotation
                mapImageLocationPin = MapImageLocationPin(with: annotation!)
                mapImageView.addSubview(mapImageLocationPin!)

                //Desired height and width
                let desiredWidth: CGFloat = 160
                let desiredHeight: CGFloat = 80
                
                //compensate for scrollView zoomscale, but never bigger than desired width amp; height!
                let width = min(desiredWidth, desiredWidth / mapImageScrollView.minimumZoomScale)
                let height = min(desiredHeight, desiredHeight / mapImageScrollView.minimumZoomScale)
                print("w: (width) x h: (height)")
                
                //center the pin image horizontal on location
                let y = location.coordinateY
                let x = location.coordinateX - (width / 2)
                
                //position (frame) the pin
                mapImageLocationPin?.frame = CGRect(x: x, y: y, width: width, height: height)
            }
        }
    }
  

Комментарии:

1. Вы пробовали viewDidLayoutSubviews ?

2. Это метод в ViewController, недоступный из моего пользовательского представления…

3. Мой плохой, вы пробовали layoutSubviews ?

4. Да, там границы и фрейм не равны нулю! Спасибо