Пользовательский UIView не загружает XIB - PullRequest
0 голосов
/ 30 января 2020

Я пытаюсь добавить настроенный UIView XIB, но происходит сбой при получении NIB.

Класс UIView .h

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface DatesView : UIView

@property (weak, nonatomic) IBOutlet UIView *contentView;

@property (weak, nonatomic) IBOutlet UILabel *fromDateLabel;
@property (weak, nonatomic) IBOutlet UILabel *fromMonthYearLabel;
@property (weak, nonatomic) IBOutlet UILabel *fromDayLabel;



@property (weak, nonatomic) IBOutlet UILabel *toDateLabel;
@property (weak, nonatomic) IBOutlet UILabel *toonthYearLabel;
@property (weak, nonatomic) IBOutlet UILabel *toDayLabel;

@end

Класс UIView .m

#import "DatesView.h"

@implementation DatesView

-(id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self initializeSubviews];
    }
    return self;
}

-(id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self initializeSubviews];

    }
    return self;
}
-(void)initializeSubviews {
    self.backgroundColor = [UIColor clearColor];

    NSBundle *bundle = [[[NSBundle mainBundle]loadNibNamed:@"DatesView" owner:self options:nil]firstObject];
    [self addSubview:self.contentView];

    self.contentView.frame = self.bounds;

}



@end

Xib

enter image description here

Отчет sh в консоли

Unknown class _TtC3EVA9DatesView in Interface Builder file.

Здесь останавливается выполнение

enter image description here

Ответы [ 2 ]

1 голос
/ 30 января 2020

Существует несколько подходов к созданию экземпляров представлений из файлов XIB. Одной из распространенных проблем является присвоение класса неправильной вещи.

Используя свой код, убедитесь, что вы присвоили класс Владельцу файла :

enter image description here

Вот упрощенный пример из вашего изображения / кода:


Источник DatesView.xib

<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="15505" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES">
    <device id="retina4_7" orientation="portrait" appearance="light"/>
    <dependencies>
        <deployment identifier="iOS"/>
        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="15510"/>
        <capability name="Safe area layout guides" minToolsVersion="9.0"/>
        <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
    </dependencies>
    <objects>
        <placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner" customClass="DatesView">
            <connections>
                <outlet property="contentView" destination="iN0-l3-epB" id="Yhm-Z4-6Rd"/>
                <outlet property="fromDateLabel" destination="cfP-lM-bLV" id="QeZ-ly-bag"/>
                <outlet property="toDateLabel" destination="WGv-5C-gVM" id="Wl6-DR-OuA"/>
            </connections>
        </placeholder>
        <placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
        <view contentMode="scaleToFill" id="iN0-l3-epB">
            <rect key="frame" x="0.0" y="0.0" width="375" height="76"/>
            <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
            <subviews>
                <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="1000" text="From Label" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="cfP-lM-bLV">
                    <rect key="frame" x="8" y="8" width="134" height="33.5"/>
                    <color key="backgroundColor" red="0.99953407049999998" green="0.98835557699999999" blue="0.47265523669999998" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                    <fontDescription key="fontDescription" type="system" pointSize="28"/>
                    <nil key="textColor"/>
                    <nil key="highlightedColor"/>
                </label>
                <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="To Label" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="WGv-5C-gVM">
                    <rect key="frame" x="266.5" y="8" width="100.5" height="33.5"/>
                    <color key="backgroundColor" red="0.97305089235305786" green="0.92194973774024858" blue="0.86304229628289908" alpha="1" colorSpace="custom" customColorSpace="displayP3"/>
                    <fontDescription key="fontDescription" type="system" pointSize="28"/>
                    <nil key="textColor"/>
                    <nil key="highlightedColor"/>
                </label>
            </subviews>
            <color key="backgroundColor" red="0.78049301826098361" green="0.95023679298999175" blue="1" alpha="1" colorSpace="custom" customColorSpace="displayP3"/>
            <constraints>
                <constraint firstItem="vUN-kp-3ea" firstAttribute="bottom" secondItem="cfP-lM-bLV" secondAttribute="bottom" priority="999" constant="8" id="8mH-tY-Xpd"/>
                <constraint firstItem="WGv-5C-gVM" firstAttribute="top" secondItem="vUN-kp-3ea" secondAttribute="top" constant="8" id="BMT-uj-nrj"/>
                <constraint firstAttribute="trailing" secondItem="WGv-5C-gVM" secondAttribute="trailing" constant="8" id="Dyv-OC-Mej"/>
                <constraint firstItem="cfP-lM-bLV" firstAttribute="leading" secondItem="vUN-kp-3ea" secondAttribute="leading" constant="8" id="Yoh-Mn-Epa"/>
                <constraint firstItem="cfP-lM-bLV" firstAttribute="top" secondItem="vUN-kp-3ea" secondAttribute="top" constant="8" id="oTg-QC-oRP"/>
            </constraints>
            <freeformSimulatedSizeMetrics key="simulatedDestinationMetrics"/>
            <viewLayoutGuide key="safeArea" id="vUN-kp-3ea"/>
            <point key="canvasLocation" x="138.40000000000001" y="330.13493253373315"/>
        </view>
    </objects>
</document>

DatesView.h

//  DatesView.h
//  Created by Don Mag on 1/30/20.

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface DatesView : UIView

@property (strong, nonatomic) IBOutlet UIView *contentView;

@property (strong, nonatomic) IBOutlet UILabel *fromDateLabel;

@property (strong, nonatomic) IBOutlet UILabel *toDateLabel;

@end

NS_ASSUME_NONNULL_END

DatesView.m

//  DatesView.m
//  Created by Don Mag on 1/30/20.

#import "DatesView.h"

@implementation DatesView

-(id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self initializeSubviews];
    }
    return self;
}

-(id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self initializeSubviews];

    }
    return self;
}
-(void)initializeSubviews {
    self.backgroundColor = [UIColor clearColor];

    NSBundle *bundle = [[[NSBundle mainBundle]loadNibNamed:@"DatesView" owner:self options:nil]firstObject];
    [self addSubview:self.contentView];

    self.contentView.frame = self.bounds;

}

@end

TestXIBViewController.h

//  TestXIBViewController.h
//  Created by Don Mag on 1/30/20.

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface TestXIBViewController : UIViewController

@end

NS_ASSUME_NONNULL_END

TestXIBViewController.m

//  TestXIBViewController.m
//  Created by Don Mag on 1/30/20.

#import "TestXIBViewController.h"
#import "DatesView.h"

@interface TestXIBViewController ()

@end

@implementation TestXIBViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    DatesView *dv = [DatesView new];
    dv.fromDateLabel.text = @"12";
    dv.toDateLabel.text = @"19";

    [self.view addSubview:dv];

    dv.translatesAutoresizingMaskIntoConstraints = NO;

    UILayoutGuide *g = [self.view safeAreaLayoutGuide];

    // constrain Top, Leading, Trailing at 40-pts
    // NO Bottom or Height constraint
    [NSLayoutConstraint activateConstraints:@[
        [dv.topAnchor constraintEqualToAnchor:g.topAnchor constant: 40.0],
        [dv.leadingAnchor constraintEqualToAnchor:g.leadingAnchor constant: 40.0],
        [dv.trailingAnchor constraintEqualToAnchor:g.trailingAnchor constant: -40.0],
    ]];

}

@end

Результат:

enter image description here

0 голосов
/ 30 января 2020

R-щелкните на xib "Владелец файла" и посмотрите, есть ли оранжевые предупреждающие треугольники. удалите ссылки, если они есть. если у вас есть что-то, ссылающееся на объект в XIB, а затем удаляющее объект, оно будет обрабатывать sh до тех пор, пока вы также не удалите ссылку.

...