UITextField doesn't scale according to width specified - ios

I want to programmatically create a UITextField and style it accordingly.
I create my Field like
let userName = UITextField(frame: CGRect(x: 60, y: 60, width: 200.00, height: 200));
userName.placeholder = "Username";
userName.textAlignment = NSTextAlignment.left;
userName.font = UIFont(name: "SpaceGrotesk-Light", size: 20.0);
userName.setBottomBorder()
view.addSubview(userName)
userName.translatesAutoresizingMaskIntoConstraints = false;
userName.leftAnchor.constraint(equalTo: view.leftAnchor,constant: 70).isActive = true;
userName.topAnchor.constraint(equalTo: WelcomeText.topAnchor,constant: 70).isActive = true;
This works but instead, the Field's width is same as the placeholder and does not increase but if you start typing in it then the field's width increases according to the text entered. I am a beginner and have no idea why this is happening.
I tried to increase the width but no luck.
let userName = UITextField(frame: CGRect(x: 60, y: 60, width: 400.00, height: 200));

First, it's best to use lower-case for the start of variable names - so instead of
let UserName = UITextField(...)
use
let userName = UITextField(...)
But, that has nothing to do with the sizing.
You appear to be trying to "mix and match" explicit frames with auto-layout. Use one or the other.
Try it like this:
// we'll use constraints, so no need to set a frame
let UserName = UITextField();
UserName.placeholder = "Username";
UserName.textAlignment = NSTextAlignment.left;
UserName.font = UIFont(name: "SpaceGrotesk-Light", size: 20.0);
UserName.setBottomBorder()
view.addSubview(UserName)
// this says "use auto-layout constraints"
UserName.translatesAutoresizingMaskIntoConstraints = false;
UserName.leftAnchor.constraint(equalTo: view.leftAnchor,constant: 70).isActive = true;
UserName.topAnchor.constraint(equalTo: WelcomeText.topAnchor,constant: 70).isActive = true;
// now, set your explicit width
UserName.widthAnchor.constraint(equalToConstant: 200.0).isActive = true
Or, if you want it to stretch based on the width of its superview:
// you have 70-pts padding from the left, so constrain to 70-pts padding from the right
// note that it should be negative (because you want it *from* the right-edge)
UserName.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -70).isActive = true

You can try using the updateConstraints or layoutIfNeeded function after created the view and configure your constraint
userName.updateConstraints()
or
userName.layoutIfNeeded()

Related

Vertical UIStackView alignment

I have a vertical UIStackview with 3 controls in it.
I want all the controls to be centered, and the first two to expand the whole width available. The third one should take 80% of the available width and be centered as well.
Here is the result I got so far:
As you can see the third control is left aligned.
Here is the code I have for all of this:
var container = new UIStackView
{
TranslatesAutoresizingMaskIntoConstraints = false,
Axis = UILayoutConstraintAxis.Vertical,
Distribution = UIStackViewDistribution.EqualCentering,
Alignment = UIStackViewAlignment.Fill,
Spacing = 10f
};
// Create the Title
UILabel title = new UILabel
{
TranslatesAutoresizingMaskIntoConstraints = false,
Text = item.name,
TextAlignment = UITextAlignment.Center,
Lines = 2,
};
container.AddArrangedSubview(title);
// Create the gauge
SFCircularGauge circularGauge = new SFCircularGauge { TranslatesAutoresizingMaskIntoConstraints = false };
circularGauge.Tag = circularGauge.GenerateViewTag();
circularGauge.HeightAnchor.ConstraintEqualTo(100f).Active = true;
#if DEBUG
circularGauge.BackgroundColor = UIColor.Cyan;
#endif
container.AddArrangedSubview(circularGauge);
// Add the evaluate button
var evaluate = UIButton.FromType(UIButtonType.RoundedRect);
evaluate.TranslatesAutoresizingMaskIntoConstraints = false;
evaluate.SetTitle(Utilities.GetLocalizedString("qol_rate_button_text"), UIControlState.Normal);
evaluate.SetTitleColor(UIColor.White, UIControlState.Normal);
evaluate.BackgroundColor = new UIColor(red: 1.00f, green: 0.37f, blue: 0.00f, alpha: 1.0f); // Optimistic Orange
evaluate.Layer.CornerRadius = 5f;
evaluate.AutoresizingMask = UIViewAutoresizing.FlexibleWidth;
evaluate.ContentEdgeInsets = new UIEdgeInsets(top: 0, left: 10f, bottom: 0, right: 10f);
evaluate.UserInteractionEnabled = true;
evaluate.TouchUpInside -= Evaluate_TouchUpInside;
evaluate.TouchUpInside += Evaluate_TouchUpInside;
evaluate.Tag = evaluate.GenerateViewTag();
viewIdsAutoEvalsIds.Add((int)evaluate.Tag, item.id);
container.AddArrangedSubview(evaluate);
evaluate.WidthAnchor.ConstraintEqualTo(container.WidthAnchor, 0.8f).Active = true;
evaluate.CenterXAnchor.ConstraintEqualTo(container.CenterXAnchor).Active = true;
I can't figure out where is my problem. In the UIStackView configuration? Somewhere else?
Thanks in advance.
The property Alignment is to sets the alignment of the non-axial subviews . In your case , you need to set it as
UIStackViewAlignment.Center
instead of
UIStackViewAlignment.Fill
This might be a bug of the control. We'll see.
In the meantime, thanks again to the Reveal Tool, the gauge has no width defined.
I solved the problem by setting the width constraint explicitly:
// Fix the width to be 100% of the container
circularGauge.WidthAnchor.ConstraintEqualTo(container.WidthAnchor).Active = true;

How to force word wrapping of UILabel that adjusts font size and is multiline

The problem I am facing is that UILabel will break line in the middle of the word although I am using word wrapping.
You can create a new project and replace content of view controller to see the result:
override func viewDidLoad() {
super.viewDidLoad()
let label = UILabel(frame: CGRect(x: 0.0, y: 0.0, width: 100.0, height: 100.0))
label.center = CGPoint(x: view.frame.midX, y: view.bounds.midY)
label.numberOfLines = 2 // Setting this to 1 produces expected result
label.lineBreakMode = .byWordWrapping
label.adjustsFontSizeToFitWidth = true
label.minimumScaleFactor = 0.5
view.addSubview(label)
label.text = "Singlewordtext"
label.backgroundColor = .red
}
This produces 2 lines of text which is broken in the middle of the word. The reason this naturally happens is because the word itself is wider than the label itself so it makes sense (I guess). But I would hope that it would use adjustsFontSizeToFitWidth and minimumScaleFactor prior to breaking it. If I set it to single line (label.numberOfLines = 1) I get expected result which is that the text will shrink instead of break. Note that doing so in this case will fit all of the text inside the label.
The question is, is there a configuration on UILabel to prevent line break in such case? Or is there some other elegant solution?
A current result:
Desired result (produced by using label.numberOfLines = 1):
Do note that I still do need to have 2 lines enabled to nicely display for instance label.text = "Three words fit".

UISlider Not displaying the Tract

I created a block to add UISlider programmatically to have total control of the design. How ever it displays on the thumb image without showing the tract. I will appreciate if anyone could help me resolve the problem.
thank you.
let ageSlider: UISlider = {
let ageS = UISlider(frame:CGRect(x: 10, y: 100, width: 300, height: 20))
ageS.minimumValue = 0
ageS.maximumValue = 60
ageS.value = 24
ageS.tintColor = .green
ageS.isContinuous = true
print("creating age slider")
//ageS.maximumTrackTintColor = UIColor.trackStrokeColor
//ageS.minimumTrackTintColor = UIColor.pulsatingFillColor
ageS.translatesAutoresizingMaskIntoConstraints = false
return ageS
}()
You need to add a width constraint to your slider object:
// add age slider constraints to age view. ageView is the container of the ageSlider
// center ageSlider both horizontally and vertically
ageSlider.centerXAnchor.constraint(equalTo: ageView.centerXAnchor).isActive = true
ageSlider.centerYAnchor.constraint(equalTo: ageView.centerYAnchor).isActive = true
// constrain ageSlider width to 90% of ageView width
ageSlider.widthAnchor.constraint(equalTo: ageView.widthAnchor, multiplier: 0.9).isActive = true
Don't set translatesAutoresizingMaskIntoConstraints to false if you want to manually set the frame of the UI component.
Either set it to true:
ageS.translatesAutoresizingMaskIntoConstraints = true
or just comment that line.
If you want the size to not be static, and change when the phone orientation changes, or when the frame of the superview changes, ..., then use constraints. In your case, you are missing the width constraint.

Font Size is either 0 or 1 (swift3)

I'm using the OpenSans font in my project but when I adjust its size to a value greater than 1, its size doesn't change. If I set its size with 0, it disappears. I don't understand why it behaves like that. Can anyone explain that to me?
Here is the code:
let RememberMe = UILabel(frame: CGRect(x: checkbox.frame.maxX + view.frame.width*0.05, y: 0, width: ForgetPasswordcontainer.frame.width*0.3, height: ForgetPasswordcontainer.frame.height/2))
RememberMe.text = "Remember Me"
RememberMe.font = UIFont(name: "OpenSans-Regular", size: 1)
RememberMe.textColor = Colors().blue
RememberMe.baselineAdjustment = .alignCenters
RememberMe.adjustsFontSizeToFitWidth = true
RememberMe.textAlignment = .center
ForgetPasswordcontainer.addSubview(RememberMe)
Its not changing because of this line:
RememberMe.adjustsFontSizeToFitWidth = true
No matter what you set the size to, once you get to that line you are once again resizing the font to fit the label that the text is contained in. Either remove that line or change the frame of the label. Also, since it is a custom font you need to be sure that you have registered it in your Info.plist.
Its working for me. Please check :
RememberMe.font = UIFont(name: "Open Sans", size: 10)
And add TTF file to your target.
hey have a look at below code
let RememberMe = UILabel(frame: CGRect(x: 10, y: 50, width: self.view.frame.size.width , height: 100))
RememberMe.text = "Remember Me"
//This add you to selected font and of minimum size which will be adjusted to width itself so no .. appears
RememberMe.font = UIFont(name: "OpenSans-Regular", size: 1000)
RememberMe.textColor = UIColor.blue
RememberMe.baselineAdjustment = .alignCenters
//Need to add this externally if you want to explicitly increase label size
RememberMe.font = UIFont.systemFont(ofSize: 100)
RememberMe.adjustsFontSizeToFitWidth = true
RememberMe.textAlignment = .center
self.view.addSubview(RememberMe)
Output :
1) Must see the frame you provide it and thats correct I think as you are taking this label in other subviews
2) need to provide RememberMe.font = UIFont.systemFont(ofSize: 100) this as to give a size to system Label you are adding as to explicitly increase minimum system font size
Hope it helps

Using CGFloat.max to size label, moving it

I'm trying to make a label multilines, that fits the screen, so i'm using the CGFloat.max to make it's height dynamic... but using CGFloat.max is causing the label to ignore the positioning, any always keep on the position 0 in the Y axis....
Even passing any variable ou even a number to it, keeps on the 0 in Y axis
Any ideas to fix??
let label: UILabel = UILabel(frame: CGRectMake(10, 50, screenWidthArea, CGFloat.max))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.ByWordWrapping
label.text = text
label.sizeToFit()
self.view.addSubview(label)
Actually I've changed CGFloat.max to 0 and it worked well... Still no idea for the reason CGFloat.max locks the label on the top of screen.
let label: UILabel = UILabel(frame: CGRectMake(10, 50, screenWidthArea, 0))

Resources