Почему мой xib-файл не отображается правильно? - PullRequest
0 голосов
/ 26 февраля 2020

Я сделал xib-файл с некоторыми кнопками и надписями, но он не отображается правильно на мой взгляд. enter image description here

В создан все выходы для этого xib в моей реализации класса file:

@property(nonatomic,retain) IBOutlet UIView *navigationView;
@property(nonatomic,retain) IBOutlet UIPageControl *pagerController;
@property(nonatomic,retain) UIImageView *arrowImage;
@property(nonatomic,retain) UILabel *steplabel;
@property(nonatomic,retain) IBOutlet UIButton *butonForward;
@property(nonatomic,retain) IBOutlet UIButton *buttonBackward;

Я хотел добавить xib в моя реализация файл:

- (void)initViewsAndLayersUsingFrame:(CGRect)frame
{

//additional setup for the map

//contains all ui elements files in an array
self.uiElements = [[NSBundle mainBundle] loadNibNamed:@"HallViewUIElements" owner:self options:nil];

[self addOverlayView:self.navigationControlView x:0 y:0];

}

addOverlayView забавный c Я написал, чтобы добавить представление как подпредставление:

- (void)addOverlayView:(UIView*)v x:(CGFloat)x y:(CGFloat)y
{
    v.hidden = YES;
    CGRect vFrame = v.frame;
    vFrame.origin.x = x;
    vFrame.origin.y = y;

    if ((v.autoresizingMask & UIViewAutoresizingFlexibleWidth) != 0) {
        vFrame.size.width = topView.bounds.size.width;
    }
    v.frame = vFrame;
    [v.layer setTransform:CATransform3DMakeTranslation(0, 0, OVERLAY_TRANSLATION_Z)];

    [overlayView addSubview:v];

}

Вот также картинка с ограничениями enter image description here Я пришел из swift и никогда ничего не делал с xib-файлами, так чего мне не хватает? Ограничения должны быть правильными. Не могу найти ошибку там.

Заранее спасибо.


ОБНОВЛЕНИЕ на основе предложенного ответа


// imports

#define OVERLAY_TRANSLATION_Z 1000

@class NavigationLocationSelection;
@class RadialGradientLayer;

@interface HallViewController : AppearanceTrackingViewController <UIScrollViewDelegate, HallElementSelectionDelegate,  NavigationManagerDelegate, TabbarSelectionNotification, TouchDownDelegate, RoundTripViewControllerDelegate,
    UIPopoverPresentationControllerDelegate,
    UINavigationControllerDelegate, UITableViewDelegate, UITableViewDataSource, CAAnimationDelegate>
{
    HallViewTestView* hallView;
    MapSource* datasource;

    UIView* wrapperView;
    UIView* overlayView;
    UIView* topView;
    CenteringScrollView* scrollView;
    CGSize scrollViewBoundsSize;
    UITouchImageView *banner;

    IBOutlet UIView *navigationControlView;
    IBOutlet UIImageView *arrowImage;
    IBOutlet UILabel *steplabel;
    SegmentedControl *barButtonSegmentedControl;
    IBOutlet SegmentedControl *barButtonSegmentedControl2;
    IBOutlet SegmentedControl *barButtonSegmentedControl3;
    IBOutlet UILabel *targetLabel;
    IBOutlet UIPageControl *pagerController;
    IBOutlet UIView *detailView;
    IBOutlet UIView *rotateHintView;
    IBOutlet UILabel *rotateLabel;
    UIImage *imgAuto, *imgAutoDisabled, *imgManual, *imgManualDisabled, *imgFavEnabled, *imgFavDisabled, *imgCompass, *imgCompassDisabled;
    BOOL ignoreSegmentedControlChange;
    UIBarButtonItem* barButtonItem;

    RadialGradientLayer* pointLayer;
    CAShapeLayer* arrowLayer;
    CAShapeLayer* deviationLayer;
    CAShapeLayer* compassLayer;
    CLLocationDirection headingAccuracy;
    // locationLayer contains pointLayer, arrowLayer, deviationLayer and compassLayer as sublayers
    CAShapeLayer* locationLayer;

    NSMutableArray<StandModel*>* stands;
    NSMutableArray* companies;
    NSMutableArray* lectures;
    MapElement_t *lastSelectedElement;
    HallViewTestView *lastSelectedHallView;

    CGPoint currentPosition;
    double currentRotation;
    double currentPitch;
    double currentRoll;
    double currentYaw;
    bool haveCurrentYaw;
    double compassRotation;
    bool haveCompassRotation;
    double pendingPitch;
    double pendingRoll;
    double pendingYaw;
    NSMutableArray* deviceMotionStack;
    bool updateRunning;
    NSLock* deviceMotionLock;
    int levelIndex;

    double currentDeviation;
    double pixelPerMeter;

    UIView *mask;
    NavigationLocationSelection *locationSelection;
    BOOL gotoNewLocation;
    BOOL waitingForLocation;

    /* routing */
    CFTimeInterval routingAnimationStartTime;
    CGPoint routingAnimationDestination;

    /* detailZoom */
    bool showingDetailMaps;
}


@property(nonatomic,retain) IBOutlet UIView *targetView;
@property(nonatomic,retain) IBOutlet UIView *navigationView;

/* routing */

@property(nonatomic,retain) IBOutlet UIButton *routingFwdBtn;
@property(nonatomic,retain) IBOutlet UIButton *routingBwdBtn;
@property(nonatomic,retain) IBOutlet UIButton *routingCloseBtn;
@property(nonatomic,retain) IBOutlet UIPageControl *pagerController;
@property(nonatomic,retain) UIImageView *arrowImage;
@property(nonatomic,retain) UILabel *steplabel;
/* detailZoom */

- (id)initWithFrame:(CGRect)frame andMapSource:(MapSource*)source;
- (void)initViewsAndLayersUsingFrame:(CGRect)frame;
// more methods for page control and so on

- (IBAction)navigateBack:(id)sender;
@end

Здесь - это файл реализации для моего HallViewController .

enter image description here enter image description here

Ответы [ 2 ]

0 голосов
/ 27 февраля 2020

В вашем вопросе отсутствует некоторая информация, но я сделал несколько предположений.

Весьма вероятно, что вы присвоили пользовательский класс не тому элементу.

Убедитесь, что у вас есть xib устанавливается следующим образом:

enter image description here enter image description here

Когда я работаю с макетами, мне нравится придавать элементам контрастные цвета фона чтобы было легко увидеть кадры. Вот что я сделал с XIB на основе вашего вопроса:

enter image description here

и вот как это выглядит во время выполнения:

enter image description here

Код для загрузки XIB и добавления его в представление выглядит следующим образом:

- (void)initViewsAndLayersUsingFrame:(CGRect)frame {

    //additional setup for the map

    //contains all ui elements files in an array
    self.uiElements = [[NSBundle mainBundle] loadNibNamed:@"HallViewUIElements" owner:self options:nil];

    // self.navigationControlView will be the first object in the array from the loaded nib
    self.navigationControlView = (HallViewUIElements *)[self.uiElements firstObject];

    // just to demonstrate calling a method in HallViewUIElements class
    [self.navigationControlView updateStepLabel:@"247 m"];

    // add navigationControlView to topView
    [self.topView addSubview:self.navigationControlView];

    // by default, the root view of a xib view has translatesAutoresizingMaskIntoConstraints set to True
    // but we can reassure ourselves
    self.navigationControlView.translatesAutoresizingMaskIntoConstraints = YES;

    // set its frame to fill topView
    self.navigationControlView.frame = self.topView.bounds;

    // set its autoresizingMask to stretch width and height
    self.navigationControlView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

}

Вот полный набор файлов, чтобы дать это тест. Добавьте их в проект и назначьте контроллер представления пользовательскому классу HallViewController:

HallViewUIElements.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"/>
        <placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
        <view contentMode="scaleToFill" id="iN0-l3-epB" customClass="HallViewUIElements">
            <rect key="frame" x="0.0" y="0.0" width="375" height="145"/>
            <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
            <subviews>
                <button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="QKi-0m-gRe">
                    <rect key="frame" x="0.0" y="0.0" width="60" height="60"/>
                    <color key="backgroundColor" red="0.81114441156387329" green="0.81952637434005737" blue="0.82378333806991577" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                    <constraints>
                        <constraint firstAttribute="height" constant="60" id="Fkc-CM-vqf"/>
                        <constraint firstAttribute="width" constant="60" id="f4z-Bz-vrg"/>
                    </constraints>
                    <state key="normal" image="chevron.left" catalog="system"/>
                </button>
                <imageView clipsSubviews="YES" userInteractionEnabled="NO" contentMode="scaleAspectFit" horizontalHuggingPriority="251" verticalHuggingPriority="251" translatesAutoresizingMaskIntoConstraints="NO" id="wEd-wZ-UKE">
                    <rect key="frame" x="70" y="0.0" width="60" height="60"/>
                    <color key="backgroundColor" red="1" green="0.15814128520000001" blue="0.31726947430000002" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                    <constraints>
                        <constraint firstAttribute="height" constant="60" id="inf-7S-Wqc"/>
                        <constraint firstAttribute="width" constant="60" id="y7z-fS-qGQ"/>
                    </constraints>
                </imageView>
                <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Go straight for" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="q6B-qU-UbB">
                    <rect key="frame" x="140" y="10" width="165" height="27.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="23"/>
                    <nil key="textColor"/>
                    <nil key="highlightedColor"/>
                </label>
                <button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="LSe-il-TBs">
                    <rect key="frame" x="315" y="0.0" width="60" height="60"/>
                    <color key="backgroundColor" red="0.81114441159999995" green="0.81952637429999997" blue="0.82378333810000004" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                    <constraints>
                        <constraint firstAttribute="width" constant="60" id="03f-mf-qu9"/>
                        <constraint firstAttribute="height" constant="60" id="Tfe-CB-hSa"/>
                    </constraints>
                    <state key="normal" image="chevron.right" catalog="system"/>
                </button>
                <pageControl opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" numberOfPages="13" currentPage="2" translatesAutoresizingMaskIntoConstraints="NO" id="EZo-CC-hbq">
                    <rect key="frame" x="88" y="98" width="199" height="37"/>
                    <color key="backgroundColor" systemColor="systemYellowColor" red="1" green="0.80000000000000004" blue="0.0" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                    <color key="pageIndicatorTintColor" white="0.66666666666666663" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
                    <color key="currentPageIndicatorTintColor" systemColor="systemRedColor" red="1" green="0.23137254900000001" blue="0.18823529410000001" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                </pageControl>
                <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="31 m" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="YAM-3s-qq4">
                    <rect key="frame" x="140" y="37.5" width="165" height="19.5"/>
                    <color key="backgroundColor" red="0.55634254220000001" green="0.97934550050000002" blue="0.0" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                    <fontDescription key="fontDescription" type="system" pointSize="16"/>
                    <nil key="textColor"/>
                    <nil key="highlightedColor"/>
                </label>
            </subviews>
            <color key="backgroundColor" red="0.24923986196517944" green="0.27383714914321899" blue="0.29557576775550842" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
            <constraints>
                <constraint firstItem="QKi-0m-gRe" firstAttribute="top" secondItem="vUN-kp-3ea" secondAttribute="top" id="2LV-tT-kBd"/>
                <constraint firstItem="YAM-3s-qq4" firstAttribute="top" secondItem="q6B-qU-UbB" secondAttribute="bottom" id="2TP-oS-moi"/>
                <constraint firstItem="q6B-qU-UbB" firstAttribute="top" secondItem="vUN-kp-3ea" secondAttribute="top" constant="10" id="31v-7L-cbl"/>
                <constraint firstItem="wEd-wZ-UKE" firstAttribute="leading" secondItem="QKi-0m-gRe" secondAttribute="trailing" constant="10" id="4zO-SB-gNw"/>
                <constraint firstItem="YAM-3s-qq4" firstAttribute="leading" secondItem="q6B-qU-UbB" secondAttribute="leading" id="BcT-Ry-OPY"/>
                <constraint firstItem="vUN-kp-3ea" firstAttribute="bottom" secondItem="EZo-CC-hbq" secondAttribute="bottom" constant="10" id="EW4-Fh-srn"/>
                <constraint firstItem="wEd-wZ-UKE" firstAttribute="top" secondItem="vUN-kp-3ea" secondAttribute="top" id="EdL-Es-n0i"/>
                <constraint firstItem="LSe-il-TBs" firstAttribute="top" secondItem="vUN-kp-3ea" secondAttribute="top" id="RLu-wg-mvF"/>
                <constraint firstItem="YAM-3s-qq4" firstAttribute="trailing" secondItem="q6B-qU-UbB" secondAttribute="trailing" id="Y5T-QI-9bp"/>
                <constraint firstItem="QKi-0m-gRe" firstAttribute="leading" secondItem="vUN-kp-3ea" secondAttribute="leading" id="ZqU-GU-x5x"/>
                <constraint firstItem="LSe-il-TBs" firstAttribute="leading" secondItem="q6B-qU-UbB" secondAttribute="trailing" constant="10" id="caY-0C-eQU"/>
                <constraint firstItem="q6B-qU-UbB" firstAttribute="leading" secondItem="wEd-wZ-UKE" secondAttribute="trailing" constant="10" id="hBe-fR-FSe"/>
                <constraint firstItem="LSe-il-TBs" firstAttribute="trailing" secondItem="vUN-kp-3ea" secondAttribute="trailing" id="hHK-yn-v8P"/>
                <constraint firstItem="EZo-CC-hbq" firstAttribute="centerX" secondItem="iN0-l3-epB" secondAttribute="centerX" id="nUb-fn-QMk"/>
            </constraints>
            <freeformSimulatedSizeMetrics key="simulatedDestinationMetrics"/>
            <viewLayoutGuide key="safeArea" id="vUN-kp-3ea"/>
            <connections>
                <outlet property="butonForward" destination="LSe-il-TBs" id="agg-Q4-c1P"/>
                <outlet property="buttonBackward" destination="QKi-0m-gRe" id="LWu-ua-dfS"/>
                <outlet property="pagerController" destination="EZo-CC-hbq" id="jUB-tU-ZnR"/>
                <outlet property="steplabel" destination="YAM-3s-qq4" id="MgI-XO-ehZ"/>
            </connections>
            <point key="canvasLocation" x="135.19999999999999" y="-102.09895052473765"/>
        </view>
    </objects>
    <resources>
        <image name="chevron.left" catalog="system" width="48" height="64"/>
        <image name="chevron.right" catalog="system" width="48" height="64"/>
    </resources>
</document>

HallViewUIElements.h

//
//  HallViewUIElements.h
//  Created by Don Mag on 2/27/20.
//

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface HallViewUIElements : UIView

- (void) updateStepLabel:(NSString *)v;

@end

NS_ASSUME_NONNULL_END

HallViewUIElements.m

//
//  HallViewUIElements.m
//  Created by Don Mag on 2/27/20.
//

#import "HallViewUIElements.h"

@interface HallViewUIElements()

// not used
//@property(nonatomic,retain) IBOutlet UIView *navigationView;

@property(nonatomic,retain) IBOutlet UIPageControl *pagerController;
@property(nonatomic,retain) IBOutlet UIButton *butonForward;
@property(nonatomic,retain) IBOutlet UIButton *buttonBackward;

@property(nonatomic,retain) IBOutlet UILabel *steplabel;

@property(nonatomic,retain) UIImageView *arrowImage;

@end

@implementation HallViewUIElements

- (void) updateStepLabel:(NSString *)v {
    self.steplabel.text = v;
}

@end

HallViewController.h

//
//  HallViewController.h
//  Created by Don Mag on 2/27/20.
//

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface HallViewController : UIViewController

@end

NS_ASSUME_NONNULL_END

HallViewController. м

//
//  HallViewController.m
//  Created by Don Mag on 2/27/20.
//

#import "HallViewController.h"
#import "HallViewUIElements.h"

#import <AVFoundation/AVFoundation.h>

@interface HallViewController ()

@property (strong, nonatomic) NSArray *uiElements;
@property (strong, nonatomic) HallViewUIElements *navigationControlView;

@property (strong, nonatomic) UIView *topView;

@end

@implementation HallViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // create topView
    self.topView = [UIView new];
    // using auto-layout
    self.topView.translatesAutoresizingMaskIntoConstraints = NO;
    // add it to self.view
    [self.view addSubview:self.topView];

    // respect safeArea
    UILayoutGuide *g = self.view.safeAreaLayoutGuide;

    [NSLayoutConstraint activateConstraints:@[

        // constrain topView Top, Leading, Trailing to safeArea with 8-pts "padding"
        [self.topView.topAnchor constraintEqualToAnchor:g.topAnchor constant:8.0],
        [self.topView.leadingAnchor constraintEqualToAnchor:g.leadingAnchor constant:8.0],
        [self.topView.trailingAnchor constraintEqualToAnchor:g.trailingAnchor constant:-8.0],

        // constrain topView Height to 120-pts (just guessing at what you want here)
        [self.topView.heightAnchor constraintEqualToConstant:120.0],

    ]];

    [self initViewsAndLayersUsingFrame:CGRectZero];
}

- (void)initViewsAndLayersUsingFrame:(CGRect)frame {

    //additional setup for the map

    //contains all ui elements files in an array
    self.uiElements = [[NSBundle mainBundle] loadNibNamed:@"HallViewUIElements" owner:self options:nil];

    // self.navigationControlView will be the first object in the array from the loaded nib
    self.navigationControlView = (HallViewUIElements *)[self.uiElements firstObject];

    // just to demonstrate calling a method in HallViewUIElements class
    [self.navigationControlView updateStepLabel:@"247 m"];

    // add navigationControlView to topView
    [self.topView addSubview:self.navigationControlView];

    // by default, the root view of a xib view has translatesAutoresizingMaskIntoConstraints set to True
    // but we can reassure ourselves
    self.navigationControlView.translatesAutoresizingMaskIntoConstraints = YES;

    // set its frame to fill topView
    self.navigationControlView.frame = self.topView.bounds;

    // set its autoresizingMask to stretch width and height
    self.navigationControlView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

}

@end
0 голосов
/ 26 февраля 2020

Попробуйте обновить кадры в viewDidLayoutSubviews, так как ваш root вид получает правильные кадры там.

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];

    // Update frames here
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...