Getting the width of a UIBarButtonSystemItem - iphone

Is there a way to programmatically get the width of a UIBarButtonSystemItem. The width property always returns 0 for system items. In particular, I want to get the exact width of the editButtonItem property of a UIViewController.
On the iPhone the value is 44 but it is a bit bigger on the iPad and I cannot nail it down.

I got my answer from the link that #JoBu1324 left of a comment.
Here is the code I used.
UIBarButtonItem *item = /*...*/;
UIView *view = [item valueForKey:#"view"];
CGFloat width = view? [view frame].size.width : (CGFloat)0.0;

Obviously UIBarButtonItem doesn't have the frame property. As UIBarButtonItem is a direct subclass of NSObject(which in turn don't have the frame), its impossible to get the frame of UIBarButtonItem from code(documented API's).
You have to rely on some other ways to find the width, as you found 44 is the width of editButtonItem in iPhone ;-)

The UIBarButtonItem has a property width, but it generally is 0 for system buttons. So, I usually use my custom button with my localized string inside the button, or use flexibleSpace UIBarbuttonItem to add a flexible space between left and right buttons. You can calculate the width of string by the method -sizeWithFont of NSString. A flexible space can be obtained by the style UIBarButtonSystemItemFlexibleSpace of UIBarButtonItem.

Related

How to set UITextField height?

I am using a UITextField. I want to increase its height but I have not found any property to do this. How can I achieve this?
You can not change the height of the rounded rect border style.
To set the height, just choose any border style other than rounded border in Xcode:
I finally found the fix for this!
As we have found, IB doesn't allow us to change the height of the rounded corner border style. So change it to any of the other styles and set the desired height. In the code change the border style back.
textField.borderStyle = UITextBorderStyleRoundedRect;
CGRect frameRect = textField.frame;
frameRect.size.height = 100; // <-- Specify the height you want here.
textField.frame = frameRect;
If you are using Auto Layout then you can do it on the Story board.
Add a height constraint to the text field, then change the height constraint constant to any desired value. Steps are shown below:
Step 1: Create a height constraint for the text field
Step 2: Select Height Constraint
Step 3: Change Height Constraint's constant value
1.) Change the border Style in the InterfaceBuilder.
2.) After that you're able to change the size.
3.) Create an IBOutlet to your TextField and enter the following code to your viewDidLoad() to change the BorderStyle back.
textField.borderStyle = UITextBorderStyleRoundedRect;
Swift 3:
textField.borderStyle = UITextBorderStyle.roundedRect
Choose the border style as not rounded
Set your height
in your viewWillAppear set the corners as round
yourUITextField.borderStyle = UITextBorderStyleRoundedRect;
Enjoy your round and tall UITextField
Follow these two simple steps and get increase height of your UItextField.
Step 1: right click on XIB file and open it as in "Source Code".
Step 2: Find the same UITextfield source and set the frame as you want.
You can use these steps to change frame of any apple controls.
An update for iOS 6 : using auto-layout, even though you still can't set the UITextField's height from the Size Inspector in the Interface Builder (as of Xcode 4.5 DP4 at least), it is now possible to set a Height constraint on it, which you can edit from the Interface Builder.
Also, if you're setting the frame's height by code, auto-layout may reset it depending on the other constraints your view may have.
I know this an old question but I just wanted to add if you would like to easily change the height of a UITextField from inside IB then simply change that UITextfield's border type to anything other than the default rounded corner type. Then you can stretch or change height attributes easily from inside the editor.
swift3
#IBDesignable
class BigTextField: UITextField {
override func didMoveToWindow() {
super.didMoveToWindow()
if window != nil {
borderStyle = .roundedRect
}
}
}
Interface Builder
Replace UITextField with BigTextField.
Change the Border Style
to none.
My pathetic contribution to this dumb problem. In IB set the style to none so you can set the height, then in IB set the class to be a subclass of UITextField that forces the style to be rounded rect.
#interface JLTForcedRoundedRectTextField : UITextField
#end
#implementation JLTForcedRoundedRectTextField
- (void)awakeFromNib
{
self.borderStyle = UITextBorderStyleRoundedRect;
}
#end
It kept me from having to hack the XIB file or writing style code into my view controller.
A UITextField's height is not adjustable in Attributes Inspector only
when it has the default rounded corners border style, but adding a
height constraint (plus any other constraints which are required to
satisfy the autolayout system - often by simply using Add Missing
Constraints) to it and adjusting the constraint will adjust the
textfield's height. If you don't want constraints, the constraints can
be removed (Clear Constraints) and the textfield will remain at the
adjusted height.
Works like a charm.
In Swift 3 use:
yourTextField.frame.size.height = 30
try this
UITextField *field = [[UITextField alloc] initWithFrame:CGRectMake(20, 80, 280, 120)];
UITextField *txt = [[UITextField alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
[txt setText:#"Ananth"];
[self.view addSubview:txt];
Last two arguments are width and height, You can set as you wish...
You can use frame property of textfield to change frame
Like-Textfield.frame=CGRECTMake(x axis,y axis,width,height)
This is quite simple.
yourtextfield.frame = CGRectMake (yourXAxis, yourYAxis, yourWidth, yourHeight);
Declare your textfield as a gloabal property & change its frame where ever you want to do it in your code.
Happy Coding!
If you're creating a lot of UITextFields it can be quicker to subclass UITextViews and override the setFrame method with
-(void)setFrame:(CGRect)frame{
[self setBorderStyle:UITextBorderStyleRoundedRect];
[super setFrame:frame];
[self setBorderStyle:UITextBorderStyleNone];
}
This way you can just call
[customTextField setFrame:<rect>];
I was having the same issue. tried some of the solutions here but rather than doing all this mumbo-jumbo. I found just setting height constraint is enough.

Get the width of a UIBarButtonItem

I'm trying to get the width of a UIBarButtonItem.
This doesn't work:
barbuttonitem.customView.frame.size.width
And this won't work, either:
barbuttonitem.width
What about this:
UIBarButtonItem *item = /*...*/;
UIView *view = [item valueForKey:#"view"];
CGFloat width = view? [view frame].size.width : (CGFloat)0.0;
I had the same problem. After a lot of tries I found something that worked!
In my specific case, I needed to get the width of the first UIBarButtonItem from the navigation controller's toolbar, but you can easily adapt it to your likings:
UIToolbar *toolbar = self.navigationController.toolbar; // or whatever toolbar you need
UIView *view = (UIView *)[toolbar.subviews objectAtIndex:0]; // 0 for the first item
double itemWidth = view.bounds.size.width;
Please note: I had to use this code in viewDidLoad to get a proper value. In the init it returns 0.0
Arthur
In case you are interested in the width on one particular item, the easiest way is to have two IBOutlets: one for the button and the other for the corresponding bar button item. Instead of reading the bar button item width, you will read the button width.
This approach, of course, will not work if you want e.g. to sum the widths in a loop. (By the way, the 1st button starts at x=12 and the distance between two buttons is 10, unless you do something tricky.) Of course, you can have two arrays, but this is just cumbersome.
There are always more than one subview in a toolbar.
In addition to arthurs answer you can iterate over them and check the type of it.
for sv in self.navigationController!.toolbar.subviews {
if sv.isKindOfClass(UIBarButtonItem.self){
let width = sv.bounds.width
}
}
Get directly width in bar button item.
UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:#"image"] style:UIBarButtonItemStylePlain target:self action:#selector(action:)];
double width = barButtonSetting.image.size.width;

Align UITableViewCell accessoryView to bottom of cell instead of middle

In the native Mail app, the To: field has a ContactAdd UIButton on the right in the accessoryView position, but it is aligned to the bottom of the cell (which you can see as the cell grows in height). Is it possible to mimic this using the accessoryView property? As far as I can tell, accessoryViews always align in the middle.
I found that you can subclass UITableViewCell, override layoutSubviews, and in that method, get the accessoryView and adjust its frame as desired.
In my app, I found a partly-working solution with the following code:
UIImage *accessoryImage = [UIImage imageNamed:#"accessory_disclosure_bottom.png"];
UIImageView *accImageView = [[UIImageView alloc] initWithImage:accessoryImage];
[accImageView setFrame:CGRectMake(0, 10, 14, 28)];
accImageView.backgroundColor = [UIColor greenColor];
accImageView.userInteractionEnabled = YES;
cell.accessoryView = accImageView;
I got the image from http://m.tech-recipes.com/rx/UITV_accessory_disclosure.png, cut away the bottom padding and made the background transparent in my graphics program. It has the full accessor functionality when selecting the row, however the image is not colored blue when selecting, which is really annoying (it seems to ignore the background transparency altogether).

Best way to add a large chunk of text to a UIScrollView?

What is the best way to display a large chunk of text (taken from a .txt file in the app) in a UIScrollView so a user can scroll about it? Length of the text is variable.
On Interface Builder open the Attributes Inspector (if not already open - command-1) and uncheck "Editable".
Also notice there's a Scroll View section below. Make sure "Scrolling" is checked.
Hope this helps somebody (the post is a year old so I guess by now the one who posted it doesn't need this info).
I came here looking for an answer and found that all answers are bad - or flat out wrong.
The proper way to do this is using UITextView by itself. Since it is a descendant of UIScrollView, it has scrolling built-in and lots of features for adjusting formatting such as the insets etc.
If you intend to only show text, you need to explicitly disable editing. You do this by setting the "editable" property to false.
And if you want to disable the text selection mechanism, set the "selectable" property to false.
In newer versions of iOS, UITextView has added support for NSTextContainer which gives you even greater control over formatting.
One way I had working for me is to create UILabel, set text and then set content size of scrollview by it size.
Here is an example
Quote:
// alocate and initialize scroll
UIScrollView *myScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 460.0f)];
// alocate and initialize label
UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 460.0f)];
// add long text to label
myLabel.text = #"Lorem ipsum... long text here";
// set line break mode to word wrap
myLabel.lineBreakMode = UILineBreakModeWordWrap;
// set number of lines to zero
myLabel.numberOfLines = 0;
// resize label
[myLabel sizeToFit];
// set scroll view size
myScroll.contentSize = CGSizeMake(myScroll.contentSize.width, myLabel.frame.size.height);
// add myLabel
[myScroll addSubview:myLabel];
// add scroll view to main view
[self.view addSubview:myScroll];
Usage of the UITextView into the UIScrollView. I could not recommend this because UITextView is the subclass of UIScrollView. Apple is also recommending the same.
Use UILabel in this case as a sub-view,
Put the UITextView into the UIScrollView.

Is there a way to change the height of a UIToolbar?

I've got an UIToolbar in Interface Builder and I've noticed that it's locked to being 44px tall. Of course I'd like to make this larger.
Does Apple allow resizing of this control? If so, how do I go about it?
Sure, just set its frame differently:
[myToolbar setFrame:CGRectMake(0, 50, 320, 35)];
This will make your toolbar 35 pixels tall. Of course this requires an IBOutlet or creating the UIToolbar programmatically, but that's very easy to do.
If that does not work in SDK 6, it is possible to solve as below:
Select the toolbar element and choose Editor > Pin > Height to create a constraint.
Go to your View Controller Scene and select the created Height(44) constraint, then put the value you want.
I found that if I set the frame on the iPad, when hiding/showing the Toolbar would reset itself back to a height of 44 pixels. I ended up having to override UIToolbar and change the method:
// return 'best' size to fit given size. does not actually resize view. Default is return existing view size
- (CGSize)sizeThatFits:(CGSize)size {
CGSize result = [super sizeThatFits:size];
result.height = 55;
return result;
};
This would correct adjust the height even with the hide/show.
In iOS 6, with autolayout, the simplest approach is a UIToolbar subclass in which you override instrinsicContentSize. Here's code from one my apps, where the toolbar is tall. Its sides and bottom are pinned to the sides and bottom of the superview as usual.
-(CGSize)intrinsicContentSize {
return CGSizeMake(UIViewNoIntrinsicMetric, 85);
}
For Xcode 7.1 iOS 9, in auto layout, the size is locked to 44px. The Xcode menu option Editor > Pin > Height is not there, instead do the following action:
In InterfaceBuilder, click the toolbar element to select it.
Control+Drag down anywhere in the toolbar and release, a popup menu will display showing the option "Height" at the top, select it.
You now have a Height constraint to work with and adjust as necessary.
You could also just edit the xib file:
open it as source code and find the entry that defines the frame for the UIToolbar, something along the lines of
<string key="NSFrame">{{0,420}, {320,44}}</string>
and just change the value for 44 to whatever size you need.
This way the toolbar will be taller, and in InterfaceBuilder you'll see the new size grayed out and you'll be unable to change it, but you don't need any outlets or code.
As long as you have a height constraint on the toolbar you can use this little snippet that has helped me adjust heights for classes that inherit from UIView
-(void)setHeightConstraintTo:(CGFloat)height forView:(UIView *)view{
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"firstAttribute = %d", NSLayoutAttributeHeight];
NSArray *filteredArray = [view.constraints filteredArrayUsingPredicate:predicate];
if(filteredArray.count > 0){
NSLayoutConstraint *constraint = filteredArray.firstObject;
constraint.constant = height;
}
}
I'm not sure how this would sit with Apple - and of course it depends how you wish to use the toolbar - but you can add a default UIView and change its class in the property inspector to UIToolbar. This gives you transparency and customisability (in this case height) for free, at the expense of the layout of bar button items.
Swift Solution:
myToolbar.frame = CGRect(x: myToolbar.frame.origin.x, y: myToolbar.frame.origin.y, width: myToolbar.frame.size.width, height: 20)
The CGRectMake is obsolete. This can be replaced with the CGRect. This will set the height of the toolbar to 20. The same works for Segmented control as well.
In interface builder, there is also the possibility to use "User Defined Runtime Attributes".
Simply add an entry with keypath set to "frame" of type "Rect" and set the value you want.