Подтвердить что ты не робот

Есть ли способ добавить ограничение между представлением и верхним макетом в файле xib?

В iOS 7 мы теперь можем добавить ограничение между представлением и верхним макетом, которое, как мне кажется, очень полезно для решения проблемы смещения строки состояния в iOS7 (особенно, когда в представлении нет панели навигации).

В файле раскадровки я могу легко добавить такие ограничения. Просто держите контрольный ключ, затем перетащите представление в контейнер, он отобразит опцию "Top Space to Top Layout Guide".

enter image description here

Но когда я делаю ту же операцию в файле xib, этот параметр исчезает.

enter image description here

Итак, есть ли способ добавить такие ограничения в xib файлах? Или мне нужно добавить их с кодом?

4b9b3361

Ответ 1

Вы должны указать следующий пример, это определенно поможет вам в решении вашей проблемы. Я получил это от http://developer.apple.com.

[button setTranslatesAutoresizingMaskIntoConstraints: NO];
id topGuide = myViewController.topLayoutGuide;
NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings (button, topGuide);

[myViewController.view addConstraints:
    [NSLayoutConstraint constraintsWithVisualFormat: @"V:[topGuide]-20-[button]"
    options: 0
    metrics: nil
    views: viewsDictionary]
];

Ответ 2

Вот мое альтернативное решение.

Найти UIView в качестве шарнира, установить его верхняя компоновка ограничение фиксированное вертикальное пространство контейнера сверху.

Control-Перетащите это ограничение макета как IBOutlet, например

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topLayoutConstraint;

Наконец, просто переопределите метод viewWillLayoutSubviews UIViewController, например, следующий

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];

    self.topLayoutConstraint.constant = [self.topLayoutGuide length] + YOUR_TOP_CONSTRSINT;
}

Все верхние ограничения других представлений основаны на этом сводном представлении, все сделано:)

Ответ 3

До сих пор даже с использованием XCode 6 я не могу выровнять элементы управления в верхнем руководстве по макету на .xib файлах. Вместо этого я использую альтернативный способ.

Во-первых, в построителе интерфейсов я по-прежнему выравниваю элементы управления до верхней границы представления viewcontroler.

Затем, в методе viewDidLoad, я заменяю некоторые ограничения, чтобы они соответствовали верхнему руководству макета вместо основного вида:

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSArray *constraints = self.view.constraints;
    for (NSLayoutConstraint *constraint in constraints) {
        if ( (constraint.firstItem == self.view) && (constraint.firstAttribute == NSLayoutAttributeTop) ) {
            NSLayoutConstraint *newConstraint = [self constraint:constraint replaceFirstItemBy:self.topLayoutGuide attribute:NSLayoutAttributeBottom];
            [self.view removeConstraint:constraint];
            [self.view addConstraint:newConstraint];
        } else if ( (constraint.secondItem == self.view) && (constraint.secondAttribute == NSLayoutAttributeTop) ) {
            NSLayoutConstraint *newConstraint = [self constraint:constraint replaceSecondItemBy:self.topLayoutGuide attribute:NSLayoutAttributeBottom];
            [self.view removeConstraint:constraint];
            [self.view addConstraint:newConstraint];
        }
    }
}

- (NSLayoutConstraint*)constraint:(NSLayoutConstraint*)constraint replaceFirstItemBy:(id)newItem attribute:(NSLayoutAttribute)newAttribute {
    UILayoutPriority priority = constraint.priority;
    NSLayoutRelation relation = constraint.relation;
    id secondItem = constraint.secondItem;
    NSLayoutAttribute secondAttribute = constraint.secondAttribute;
    CGFloat multiplier = constraint.multiplier;
    CGFloat constant = constraint.constant;

    NSLayoutConstraint *newConstraint = [NSLayoutConstraint constraintWithItem:newItem attribute:newAttribute relatedBy:relation toItem:secondItem attribute:secondAttribute multiplier:multiplier constant:constant];
    newConstraint.priority = priority;
    return newConstraint;
}

- (NSLayoutConstraint*)constraint:(NSLayoutConstraint*)constraint replaceSecondItemBy:(id)newItem attribute:(NSLayoutAttribute)newAttribute {
    UILayoutPriority priority = constraint.priority;
    id firstItem = constraint.firstItem;
    NSLayoutAttribute firstAttribute = constraint.firstAttribute;
    NSLayoutRelation relation = constraint.relation;
    CGFloat multiplier = constraint.multiplier;
    CGFloat constant = constraint.constant;

    NSLayoutConstraint *newConstraint = [NSLayoutConstraint constraintWithItem:firstItem attribute:firstAttribute relatedBy:relation toItem:newItem attribute:newAttribute multiplier:multiplier constant:constant];
    newConstraint.priority = priority;
    return newConstraint;
}

Подумайте, что это не лучший способ, потому что мы заменяем объекты, которые мы определяем в построителе интерфейса. Но это может быть альтернативный способ, о котором мы можем думать.

Ответ 4

Конечно, вы можете не только добавлять ограничение между представлением и top layout guide или bottom layout guide программным способом, но также вы можете удалить и получить доступ к ограничению между представлением и top and bottom layout guide с помощью KVConstraintExtensionsMaster библиотека.

// create containerView
UIView *containerView = [UIView prepareNewViewForAutoLayout];
[containerView setBackgroundColor:[UIColor brownColor]];
[self.view addSubview:containerView];

// To add Top and Bottom Layout Guide constraint of containerView
[self applyTopLayoutGuideConstraintToView:containerView withPadding:0];
[self applyBottomLayoutGuideConstraintToView:containerView withPadding:50];

// To access top Layout Guide Constraint and update it constant value.
NSLayoutConstraint *topLayoutGuideConstraint = [self accessAppliedTopLayoutGuideConstraintFromView:containerView];
topLayoutGuideConstraint.constant = 50;

// To access bottom Layout Guide Constraint and update it constant value with animation
NSLayoutConstraint *bottomLayoutGuideConstraint = [self accessAppliedBottomLayoutGuideConstraintFromView:containerView];
bottomLayoutGuideConstraint.constant = 80;
[self.view updateModifyConstraintsWithAnimation:NULL]; // call this for animation

// To remove Top and Bottom Layout Guide constraint of containerView
[self removeAppliedTopLayoutGuideConstraintFromView:containerView];
[self removeAppliedBottomLayoutGuideConstraintFromView:containerView ];

Ответ 5

Из iOS 9 вы также можете сделать это более простым с помощью topLayoutGuide anchors:

  • Swift 3

view.topAnchor.constraint(equalTo: self.topLayoutGuide.bottomAnchor).isActive = true

  • ObjC

[controller.view.topAnchor constraintEqualToAnchor:controller.topLayoutGuide.bottomAnchor].active = YES;

Ответ 6

Я думаю, что причина, по которой они не появляются в XIB, заключается в том, что в этой ситуации нет знаний о иерархии диспетчера представлений, тогда как в доске истории IB может определить, откуда находятся направляющие из иерархии диспетчера представлений находится внутри. Т.е. если он содержится в UINavigationController, он может определить, что верхнее руководство по макету находится под панелью навигации.

Ответ 7

Ответ Cao Huu Loc с быстрым 4

extension NSLayoutConstraint {

    func constraintReplacing(firstItemWith newFirstItem: UILayoutSupport, withAttribute newFirstAttribute: NSLayoutAttribute) -> NSLayoutConstraint {
        return NSLayoutConstraint(item: newFirstItem, attribute: newFirstAttribute, relatedBy: relation, toItem: secondItem, attribute: secondAttribute, multiplier: multiplier, constant: constant)
    }

    func constraintReplacing(secondItemWith newSecondItem: UILayoutSupport, withAttribute newSecondAttribute: NSLayoutAttribute) -> NSLayoutConstraint {
        return NSLayoutConstraint(item: firstItem as Any, attribute: firstAttribute, relatedBy: relation, toItem: newSecondItem, attribute: newSecondAttribute, multiplier: multiplier, constant: constant)
    }
}

class YourViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        for constraint in view.constraints {
            if constraint.firstItem === view && constraint.firstAttribute == .top {
                let newConstraint = constraint.constraintReplacing(firstItemWith: topLayoutGuide, withAttribute: .bottom)
                view.removeConstraint(constraint)
                view.addConstraint(newConstraint)
            }
            if constraint.secondItem === view && constraint.secondAttribute == .top {
                let newConstraint = constraint.constraintReplacing(secondItemWith: topLayoutGuide, withAttribute: .bottom)
                view.removeConstraint(constraint)
                view.addConstraint(newConstraint)
            }
        }
    }
}