Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
931 views
in Technique[技术] by (71.8m points)

objective c - Align Toolbar Item to split view content unsing Auto Layout Constraints

I would like to align a button in the toolbar of an os x app to the position of a split view in the window, similar to the delete button in Apple Mail. How can this be done using auto layout constraints?

I did find a hint in apples documentation according to which it should be possible to use auto layout constraints (at https://developer.apple.com/library/ios/documentation/userexperience/conceptual/AutolayoutPG/AutoLayoutConcepts/AutoLayoutConcepts.html), where it says that "Constraints can, with some restrictions, cross the view hierarchy. In the Mail app in OS X, for example, by default the Delete button in the toolbar lines up with the message table". But that is unfortunately all I could find.

I tried to create a constraint between the content of the left splitView pane and the button:

NSView *button = self.toolbarItemButton.view;
NSView *leftPane = self.leftSplitContent;

[self.window.contentView addConstraints:[NSLayoutConstraint
    constraintsWithVisualFormat:@"[leftPane][button]"
    options:0 metrics:nil
    views:NSDictionaryOfVariableBindings(leftPane, button)]
];

But I then get an error message that seems to indicate that cross-view constraints are not possible: "constraint references something from outside the subtree of the view" Is there any way to do this?

A workaround I found was to not use constraints, but instead insert a custom view (not a spacer!) to the left of the button. I can then change the size of that view to move the button... However, this seems more like a hack to me.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I know it's a bit old, but I had the same issue and found an answer:

You have to use topLayoutGuide property.

Ex in swift

view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormats(
        ["H:|[toolbarShadow]|", "V:[topLayoutGuide][toolbarShadow(100)]"], 
views: viewDictionnary))

Of course topLayoutGuide must be in your view dictionary

You can access it through self.topLayoutGuide


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...