ios draw rectangle with top right corner - ios

I am trying to make a rect which is drawn using it's top right corner (x,y) instead of the usual top left. I tried scaling by -1, but that didn't do the work.
I need it because I am developing an app for RTL locale.

If you use auto layout, you can use the leading and trailing constraints (rather than left and right constraints) and the animation will automatically be adjusted for the target language. For example, consider the following simplistic demo that overlays a "curtain" view, and then, two seconds later "pulls it aside" by animating the trailing constraint:
let curtain = UIView()
curtain.backgroundColor = .darkGrayColor()
curtain.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(curtain)
let trailingConstraint = curtain.trailingAnchor.constraintEqualToAnchor(view.trailingAnchor)
NSLayoutConstraint.activateConstraints([
curtain.leadingAnchor.constraintEqualToAnchor(view.leadingAnchor),
curtain.topAnchor.constraintEqualToAnchor(view.topAnchor),
curtain.bottomAnchor.constraintEqualToAnchor(view.bottomAnchor),
trailingConstraint
])
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(2 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) {
trailingConstraint.constant = -self.view.bounds.size.width
UIView.animateWithDuration(0.5) {
self.view.layoutIfNeeded()
}
}
If your project's localization is a LTR language, it will animate the pulling back of this "curtain" from the right edge.
But if you project's localization is a RTL language, such as shown below, then it will animate the pulling of this "curtain" from the left edge:

Related

Centering between two anchors

I want to set a centerYAnchor between two anchors. Similar to this:
centeredLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor),
However, I don't want it to be centered relative to the screen. I want it to be right in between two other anchors on the screen. Like if I have a toolbar at the top like this:
toolbar.topAnchor.constraint(equalTo: view.topAnchor),
Then I have a button at the bottom like this:
button.bottomAnchor.constraint(equalTo: guide.bottomAnchor, constant: -20)
is there a way I can center centeredLabel's y constraint to be right between the bottomanchor of toolbar and the top anchor of button?
is there a way I can center centeredLabel's y constraint to be right between the bottomanchor of toolbar and the top anchor of button?
Yes, there is. The simple way is to use a transparent spacer view whose top is anchored to the upper anchor and whose bottom is anchored to the lower anchor. Now you center-anchor your label to the center of the spacer view.
However, although that is simple, it is not the best way. The best way is to create, instead of a transparent spacer view, a custom UILayoutGuide. Unfortunately this can be done only in code, not in the storyboard (whereas the spacer view and label can be configured entirely in the storyboard). But it has the advantage that it doesn't burden the rendering tree with an additional view.
Here's your situation, more or less, using a button as the upper view and a button as the lower view. The label is centered vertically between them:
Here's the code that generated that situation. b1 and b2 are the buttons (and it doesn't matter how they are created and positioned):
let g = UILayoutGuide()
self.view.addLayoutGuide(g)
g.topAnchor.constraint(equalTo: b1.bottomAnchor).isActive = true
g.bottomAnchor.constraint(equalTo: b2.topAnchor).isActive = true
g.leadingAnchor.constraint(equalTo:b1.leadingAnchor).isActive = true
g.trailingAnchor.constraint(equalTo:b1.trailingAnchor).isActive = true
let lab = UILabel()
lab.text = "Label"
lab.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(lab)
lab.leadingAnchor.constraint(equalTo:g.leadingAnchor).isActive = true
lab.centerYAnchor.constraint(equalTo:g.centerYAnchor).isActive = true
Although #matt's solution works, here is a simpler one that uses autolayout without the need to create a UILayoutGuide.
iOS 10 introduced a simple way of doing this through NSLayoutXAxisAnchor.anchorWithOffset(to:) and NSLayoutYAxisAnchor.anchorWithOffset(to:).
Here are convenience methods which wrap up this logic.
For X axis centering
extension NSLayoutXAxisAnchor {
func constraint(between anchor1: NSLayoutXAxisAnchor, and anchor2: NSLayoutXAxisAnchor) -> NSLayoutConstraint {
let anchor1Constraint = anchor1.anchorWithOffset(to: self)
let anchor2Constraint = anchorWithOffset(to: anchor2)
return anchor1Constraint.constraint(equalTo: anchor2Constraint)
}
}
For Y axis centering
extension NSLayoutYAxisAnchor {
func constraint(between anchor1: NSLayoutYAxisAnchor, and anchor2: NSLayoutYAxisAnchor) -> NSLayoutConstraint {
let anchor1Constraint = anchor1.anchorWithOffset(to: self)
let anchor2Constraint = anchorWithOffset(to: anchor2)
return anchor1Constraint.constraint(equalTo: anchor2Constraint)
}
}
To do what you need you can call:
centeredLabel.centerYAnchor.constraint(between: toolbar.bottomAnchor, and: button.topAnchor)

MKMapView's scale is not shown

I'm doing an iOS application. In Xcode 9.1 I create a MKMapView by
let mapView = MKMapView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height))
mapView.isUserInteractionEnabled = false
mapView.mapType = .satellite
mapView.showsCompass = false
mapView.showsScale = true
view.addSubview(mapView)
but when I run it in the simulator the scale is not shown and I get three messages in the log:
Could not inset compass from edges 9
Could not inset scale from edge 9
Could not inset legal attribution from corner 4
The compass is not shown (as expected) but it's not shown if I change mapView.showsCompass to trueeither. However, the Legal link is shown. What am I missing here? I'm guessing it's something about the new safe areas introduced with iOS 11, but I fail to see how that is important for a view I want to be covering the whole screen.
In iOS 10 or lower
As #Paulw11 says, the scale is only shown while zooming by default.
In iOS 11
You can use scaleVisibility.
https://developer.apple.com/documentation/mapkit/mkscaleview/2890254-scalevisibility
let scale = MKScaleView(mapView: mapView)
scale.scaleVisibility = .visible // always visible
view.addSubview(scale)
had the same problem with the scale today. I want that scale visible all the time. Cost me several hours to solve it. So I add the code here, just in case, someone run into the same issue.
Got some hints:
from this thread: Use Safe Area Layout programmatically
and this website: Pain Free Constraints with Layout Anchors
Happy coding ...
Hardy
// "self.MapOnScreen" refers to the map currently displayed
// check if we have to deal with the scale
if #available(iOS 11.0, *) {
// as we will change the UI, ensure it's on main thread
DispatchQueue.main.async(execute: {
// switch OFF the standard scale (otherwise both will be visible when zoom in/out)
self.MapOnScreen.showsScale = false
// build the view
let scale = MKScaleView(mapView: self.MapOnScreen)
// we want to use autolayout
scale.translatesAutoresizingMaskIntoConstraints = false
// scale should be visible all the time
scale.scaleVisibility = .visible // always visible
// add it to the map
self.MapOnScreen.addSubview(scale)
// get the current safe area of the map
let guide = self.MapOnScreen.safeAreaLayoutGuide
// Activate this array of constraints, which at the time removes leftovers if any
NSLayoutConstraint.activate(
[
// LEFT (I do not want a change if right-to-left language) margin with an offset to safe area
// alternative would be ".leadingAnchor", which switches to the right margin, if right-to-left language is used
scale.leftAnchor.constraint(equalTo: guide.leftAnchor, constant: 16.0),
// right edge will be the middle of the map
scale.rightAnchor.constraint(equalTo: guide.centerXAnchor),
// top margin is the top safe area
scale.topAnchor.constraint(equalTo: guide.topAnchor),
// view will be 20 points high
scale.heightAnchor.constraint(equalToConstant: 20.0)
]
)
})
}
Objective c equivalent:-
if (#available(iOS 11.0, *)) {
// switch OFF the standard scale (otherwise both will be visible when zoom in/out)
self.map.showsScale = false;
// build the view
MKScaleView* scale = [MKScaleView scaleViewWithMapView:self.map];
// we want to use autolayout
scale.translatesAutoresizingMaskIntoConstraints = false;
// scale should be visible all the time
scale.scaleVisibility = MKFeatureVisibilityVisible;// always visible
// add it to the map
[self.view addSubview:scale];
// get the current safe area of the map
UILayoutGuide * guide = self.view.safeAreaLayoutGuide;
// Activate this array of constraints, which at the time removes leftovers if any
[NSLayoutConstraint activateConstraints:
#[
// LEFT (I do not want a change if right-to-left language) margin with an offset to safe area
// alternative would be ".leadingAnchor", which switches to the right margin, if right-to-left language is used
//[scale.leftAnchor constraintEqualToAnchor: guide.centerXAnchor constant: -(scale.frame.size.width/2.0)],
// right edge will be the middle of the map
[scale.rightAnchor constraintEqualToAnchor: guide.centerXAnchor constant: (scale.frame.size.width/2.0)],
// top margin is the top safe area
[scale.bottomAnchor constraintEqualToAnchor: guide.bottomAnchor constant:-self.toolBar.frame.size.height],
// view will be 20 points high
[scale.heightAnchor constraintEqualToConstant: 50.0]
]
];
[self.view bringSubviewToFront:scale];
}

How to animate centered square to the top

I have a UIView in a portrait-only app.
The view is centered vertically and horizontally with AutoLayout ("manually" using storyboards).
The width equals the (main)view.width * 0.9
The height is the same size of the width (it is a square).
I want to tap a button inside this UIView and animate it only vertically until it reaches the top border of the screen (eg. height*0.9, 10 pts, whatever is possible).
When I click again, I want to reposition back the view to its original position (centered as it was when I first tapped).
During the transition the square should not be tappable.
After reading many posts I could not understand what's the best way to do this (I red mainly developers saying old techniques using centerX should be avoided and lamentations about some versions of the SO behaving in strange ways).
I suppose I should find a way to get the current "position" of the constraints and to assign a constraint the "final" position, but I was not able to do it.
Any help is appreciated
You are all going the wrong way about this.
Add one constraint that pins the view to the top, and add one constraint that pins the view to centerY. It will complain, so pick one and disable it (I think the property in Interface Builder is called Installed).
If the initial state is the view in the center, disable the constraint that pins it to the top, and viceversa.
Now write IBOutlets for both constraints in your controller and connect them to those constraints. Make sure the declaration of that variable is not weak, otherwise the variable will become nil when the constraint is disabled.
Whenever you want to toggle your animation you can enable one constraint and disable the other.
#IBOutlet var topConstraint: NSLayoutConstraint!
#IBOutlet var centerConstraint: NSLayoutConstraint!
func toggleState(moveToTop: Bool) {
UIView.animateWithDuration(0.25) {
self.topConstraint.isActive = moveToTop
self.centerConstraint.isActive = !moveToTop
self.view.layoutIfNeeded()
}
}
While you can use Autolayout to animate - to take the constraint constraining the centerY and set its constant to a value that would move to the top (e.g., constant = -(UIScreen.main.bounds.height / 2)), I would recommend using view's transform property.
So to move the view to the top you can use:
let topMargin = CGFloat(20)
let viewHalfHeight = self.view.bounds.height / 2
let boxHalfHeight = self.box.bounds.height / 2
UIView.animate(withDuration: 0.2) {
box.transform = CGAffineTransform.identity
.translatedBy(x: 0, y: -(viewHalfHeight - (boxHalfHeight + topMargin)))
}
You are moving box.center related to the view.center - so if you want to move the box to the top, you have to move its center by half a view's height (because the view's centerY is exactly height / 2 far from the view's top). That is not enough though, because then only a bottom half of the box is visible (now the box.centerY == view.top). Therefore you have to move it back by the box.bounds.height / 2 (in my code boxHalfHeight) - to make the top half visible. And to that boxHalfHeight you add topMargin so that there is some margin to the top.
Then, to move the box back to original position:
UIView.animate(withDuration: 0.2) {
box.transform = CGAffineTransform.identity
}
EDIT
If you really want to go with autolayout, you have to have a reference to the centerY constraint, so for example if it is created this way:
let boxCenterYConstraint = self.box.centerYAnchor.constraint(equalTo: self.view.centerYAnchor)
boxCenterYConstraint.isActive = true
Then you can try this:
// calculating the translation is the same
let topMargin = CGFloat(20)
let viewHalfHeight = self.view.bounds.height / 2
let boxHalfHeight = self.box.bounds.height / 2
let diff = -(viewHalfHeight - (boxHalfHeight + topMargin))
boxCenterYConstraint.constant = diff
self.view.setNeedsLayout()
UIView.animate(withDuration: 0.2) {
self.view.layoutIfNeeded()
}
And animation back:
boxCenterYConstraint.constant = 0
self.view.setNeedsLayout()
UIView.animate(withDuration: 0.2) {
self.view.layoutIfNeeded()
}

Align an Icon to the top left of multiline UILabel

On the top left on a UILabel I want to align an Icon. This works file but if the Label has multiple lines the UIImage is aligned in the middle of the UILabel. There are option on interface builder such as first base line, but what I need is something like first line center Y. Is there something similar?
Actually there is a way of doing this! If you use AutoLayout this can be done with the following snippet:
// Aligns the icon to the center of a capital letter in the first line
let offset = label.font.capHeight / 2.0
// Aligns the icon to the center of the whole line, which is different
// than above. Especially with big fonts this makes a visible difference.
let offset = (label.font.ascender + label.font.descender) / 2.0
let constraints: [NSLayoutConstraint] = [
imageView.centerYAnchor.constraint(equalTo: label.firstBaselineAnchor, constant: -offset),
imageView.trailingAnchor.constraint(equalTo: label.leadingAnchor, constant: -10)
]
NSLayoutConstraint.activate(constraints)
The first constraint will display your icon at the Y center of the first line of your label. The second one puts your icon left of the label and creates a 10pt space between them.
Just put constraints as shown in the above image.
Hint: I made label's lines property value to 5 which supports upto 5 lines without any compromise.

How do i make the constraints resize the buttons correctly?

I've added a stoplight image and red, yellow, and green buttons. I want to have the buttons resize to iPhone 4S and iPhone 6S screens, but the buttons either disappear off the page or are the wrong size for the iPhone 4S. I thought the number of point would resize proportionately, but it appears it does not. Any help would be appreciated, I really want to understand constraints but I am just not getting it! Normally I would just do a x-position/screensize, y-position/screensize to relocated it, but this could be noticeably too long.
Here is the constraints of the latest incorrect location. When I try to select the stoplight image, it won't provide a constraint for the leading and trailing edge to the stoplight image.
The yellow button is placed against the stoplight image, but it won't resize.
The easiest solution would be to give all images fixed values for their width and height constraints. Then you can align the spotlightImage in the superview as you wish and define the alignment of the circle images relative to the stoplight image.
However, if you would like to stretch the width of the stoplight image depending on the width of the screen, this is a complex problem. I played around a bit trying to define all constraints in storyboard, but could not come up with a proper solution. What one ideally would like to do, for example, is define the centreX of the circles proportionally to the spotlight image's width. Similarly for the y position. Unfortunately this is not possible.
In code one have a little bit more control. Here is a solution that will work. It is not pretty, because you are actually recalculating the width of the spotlightImage, but it works :-)
class ViewController: UIViewController {
lazy var stopLightImageView: UIImageView = {
return UIImageView(image: UIImage(named:"stopLight"))
}()
lazy var circleImageView: UIImageView = {
return UIImageView(image: UIImage(named:"circle"))
}()
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
}
private func setupViews() {
//Values at start. This is used to calculate the proportional values, since you know they produce the correct results.
let stoplightStartWidth: CGFloat = 540
let stoplightStartHeight: CGFloat = 542
let circleStartWidth: CGFloat = 151
let circleStartLeading: CGFloat = 231
let circleStartTop: CGFloat = 52
let screenWidth = UIScreen.mainScreen().bounds.size.width
let stoplightMargin: CGFloat = 20
self.view.addSubview(stopLightImageView)
stopLightImageView.translatesAutoresizingMaskIntoConstraints = false
//stoplightImage constraints
stopLightImageView.leadingAnchor.constraintEqualToAnchor(self.view.leadingAnchor, constant: stoplightMargin).active = true
stopLightImageView.trailingAnchor.constraintEqualToAnchor(self.view.trailingAnchor, constant: -stoplightMargin).active = true
stopLightImageView.centerYAnchor.constraintEqualToAnchor(self.view.centerYAnchor, constant: 0).active = true
stopLightImageView.heightAnchor.constraintEqualToAnchor(stopLightImageView.widthAnchor, multiplier: stoplightStartWidth/stoplightStartHeight).active = true
self.view.addSubview(circleImageView)
circleImageView.translatesAutoresizingMaskIntoConstraints = false
//circle constraints
circleImageView.widthAnchor.constraintEqualToAnchor(stopLightImageView.widthAnchor, multiplier: circleStartWidth/stoplightStartWidth).active = true
circleImageView.heightAnchor.constraintEqualToAnchor(circleImageView.widthAnchor, multiplier: 1).active = true
let stoplightWidth = screenWidth - 2*stoplightMargin
let stoplightHeight = stoplightWidth * stoplightStartHeight/stoplightStartWidth
circleImageView.leadingAnchor.constraintEqualToAnchor(stopLightImageView.leadingAnchor, constant: stoplightWidth*circleStartLeading/stoplightStartWidth).active = true
circleImageView.topAnchor.constraintEqualToAnchor(stopLightImageView.topAnchor, constant: stoplightHeight*circleStartTop/stoplightStartHeight).active = true
}
}
Constraints are tricky, and it looks like you have a lot going on there. It's hard to tell you exactly what to do for this so, here's what I would try to do if I was having this issue(hopefully one works for you):
Set the images in the Attributes Inspector to either Aspect Fit or Redraw... That should fix your issue with them being different shapes.
Also look through the list of constraints to see if one relies on another, (for example the red and yellow seem to have similar constraints). If they rely on each other, ensure to satisfy any constraints that aren't yet - based off of the "parent" image.
Select everything and set to "Reset to Suggested Constraints". Build and run. If that doesn't fix it then there's only a few things left you can do.
Remove all the constraints on every object. Start with the black image and add missing constraints... or set it to "Center Horizontally in Container". Right click and drag the image or asset to your "view" or to the yellow "First" circle located above.
Hopefully this helps.

Resources