How to adjust size of UITextView automatically ? - uitextview

I want to make speech bubbles but there is a problem adjusting size of the bubbles in UITextView.
is there a way to increase the size of the Textview automatically depending on the length of the
text by using UITextView?

Okay I found a better way of doing what I was suggesting. Rather then deal with the UIView and resizing depending on the text inside it. I just made the UITextView have a rounded edge which now looks like a panel. Perfect. Hope this helps someone!
If your interested in the code
- (void)drawRect:(CGRect)rect
{
CGRect frame = self.frame;
frame.size.height = self.contentSize.height;
self.frame = frame; // Drawing code
self.clipsToBounds = YES;
self.layer.cornerRadius = 10.0f;
}

I think I understand what your getting at. I had this problem the other day. This bit of code will adjust the UITextView contents. Create a new class and call this into it via a new class. If you want to adjust the View well I'm still working on that :-P
Hope this helps
- (void)drawRect:(CGRect)rect
{
CGRect frame = self.frame;
frame.size.height = self.contentSize.height;
self.frame = frame; // Drawing code
}

Related

How to move a UIImage 100px to the right only

In Xamarin iOS, how can I simply move an image to the right 100px from its current location? I know that I am suppose to use Bounds, but I can't get the intenseness to really provide anything helpful. I have googled it and there isn't much that I can find.
Assuming you mean an UIImageView, you can use the Offset(dx,dy) method on its Frame property. If your UIImageView is called imageView:
var frame = imageView.Frame;
frame.Offset(100,0); // offset 100px horizontal, 0 px vertical
imageView.Frame = frame; // set the frame of the image to the new position.
Note that you must take the frame object into a seperate variable. That is, imageView.Frame.Offset(100,0) will not work.

Image scaling,make it it fit to bounds of UITableView cell with maintaining color combination and image quality in monotouch

Problem:
I have used following code for scaling image and make it fit to bounds of UITableviewCell in monotouch.This code is scaling image but it is making image color faint means it is not maintaining color combination.So please provide any better solution.
Code:
public static UIImage Scale (UIImage source, SizeF newSize)
{
UIGraphics.BeginImageContext (newSize);
var context = UIGraphics.GetCurrentContext ();
context.TranslateCTM (0, newSize.Height);
context.ScaleCTM (1f, -1f);
context.DrawImage (new RectangleF (0, 0, newSize.Width, newSize.Height), source.CGImage);
var scaledImage = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
return scaledImage;
}
If you want scale UIImage, then see this method. It works fine. You should cache method's result in file system to avoid image scaling on every GetCell.
If you source images are the same or almost the same size like UIImageViews in UITableViewCell Mohib Sheth solution with setting ContentMode property is best. It source image have much greater size than UIImageViews in UITableViewCell, scrolling speed will be lower.
Read all about ContentMode for UIView in iOS here
For your requirement you would need to set the ContentMode property to UIViewContentModeScaleAspectFit
I cant help you with a sample code, since you haven't provided any code on how you are creating & populating the TableView.

uiscrollview for scrolling a very, very tall page

From top to bottom I have UIView, UIScrollView, a UIImage, a UILabel, a UITextView and a UIButton.
My reason behind the top-most UIScrollView was so the whole vertical content would scroll.
What I really need a substitute for is the UITextView (5th down) because the UITextView is a subclass of UIScrollView. And this substitute must accomodate the very tall column of formatted text.
What I don't want is a scrollable object in the middle of the page; I want the whole page to be scrollable.
One more thing ... please note there's a button immediately below this tall column of text.
John Love
THANK YOU! Ashack and Pentagp. I guess I finally had to surrender and dump the idea that IB could be used for all GUI ...
The entire UIView contains a UILabel, a UIImage, a UITextView and
a UIButton at the very bottom.
The goal here was to make this entire content scrollable.
Thanks to you guys at stackoverflow.com:
using IB, un-check "Scrolling Enabled" for the UITextView
because it's a concrete type of UIScrollView
using IB, drag a UIScrollView to the UIView and match sizes and
insure that the UIScrollView encloses all sub-views
make the UITextView height = its contentSize.height
move the UIButton to below this UITextView
and then, thanks to iphonedevsdk.com:
adjust the contentSize.height of the top-most UIScrollview to
include the height of the re-positioned UIButton
Problem solved!!!
Your question is not very specific, but I think you're asking how to make a text view that does not scroll, and expands to fit the text. You can do this with UILabel, but it's a multi-step process. The same will work for UITextView if you disable scrolling and set the contentSize to match the frame dimensions.
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100,100,100,100)];
label.font = [UIFont systemFontOfSize:24];
NSString *yourTextString = #"your text";
CGSize maximumLabelSize = CGSizeMake(100, 500);
CGSize expectedLabelSize = [yourTextString sizeWithFont:label.font
constrainedToSize:maximumLabelSize
lineBreakMode:yourLabel.lineBreakMode];
CGRect labelFrame = label.frame;
labelFrame.size.width = expectedLabelSize.width;
labelFrame.size.height = expectedLabelSize.height;
label.frame = labelFrame;
Then from there, use the label's frame to set the position of the button and all elements below it.
If I understand your problem, you don't want nested scroll.
So set yourTextView.scrollEnabled = NO; //Do it programmatically our in the nib
Also in order to display all the text set yourTextView frame height to its content height:
yourTextView.frame = CGRectMake(yourTextView.frame.origin.x,
yourTextView.frame.origin.y,
yourTextView.frame.size.width,
yourTextView.contentSize.height + (yourTextView.contentSize.width > yourTextView.frame.size.width ? (yourTextView.contentSize.width * yourTextView.contentSize.height / (yourTextView.contentSize.width - yourTextView.frame.size.width)) - yourTextView.contentSize.height :0)));
/*
If textView is dynamically filled, you have to check if yourTextView.contentSize.width is bigger than yourTextView.frame.size.width then add proportionally what is remaining to the height.
*/
At the end change your button position if needed:
yourbutton.frame = CGRectMake(yourbutton.frame.origin.x,
yourTextView.frame.origin.y + yourTextView.frame.size.height + 20, //If you want your button to be 20 point after your textView
yourbutton.frame.size.width,
yourbutton.frame.size.height);
Hope that will help you...

Resize CATextLayer to fit text on iOS

All my research so far seems to indicate it is not possible to do this accurately. The only two options available to me at the outset were:
a) Using a Layout manager for the CATextLayer - not available on iOS as of 4.0
b) Use sizeWithFont:constrainedToSize:lineBreakMode: and adjust the frame of the CATextLayer according to the size returned here.
Option (b), being the simplest approach, should work. After all, it works perfectly with UILabels. But when I applied the same frame calculation to CATextLayer, the frame was always turning out to be a bit bigger than expected or needed.
As it turns out, the line-spacing in CATextLayers and UILabels (for the same font and size) is different. As a result, sizeWithFont (whose line-spacing calculations would match with that of UILabels) does not return the expected size for CATextLayers.
This is further proven by printing the same text using a UILabel, as against a CATextLayer and comparing the results. The text in the first line overlaps perfectly (it being the same font), but the line-spacing in CATextLayer is just a little shorter than in UILabel. (Sorry I can't upload a screenshot right now as the ones I already have contain confidential data, and I presently don't have the time to make a sample project to get clean screenshots. I'll upload them later for posterity, when I have the time)
This is a weird difference, but I thought it would be possible to adjust the spacing in the CATextLayer by specifying the appropriate attribute for the NSAttributedString I use there, but that does not seem to be the case. Looking into CFStringAttributes.h I can't find a single attribute that could be related to line-spacing.
Bottomline:
So it seems like it's not possible to use CATextLayer on iOS in a scenario where the layer is required to fit to its text. Am I right on this or am I missing something?
P.S:
The reason I wanted to use CATextLayer and NSAttributedString's is because the string to be displayed is to be colored differently at different points. I guess I'd just have to go back to drawing the strings by hand as always....of course there's always the option of hacking the results from sizeWithFont to get the proper line-height.
Abusing the 'code' tags a little to make the post more readable.
I'm not able to tag the post with 'CATextLayer' - surprisingly no such tags exist at the moment. If someone with enough reputation bumps into this post, please tag it accordingly.
Try this:
- (CGFloat)boundingHeightForWidth:(CGFloat)inWidth withAttributedString:(NSAttributedString *)attributedString {
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString( (CFMutableAttributedStringRef) attributedString);
CGSize suggestedSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0, 0), NULL, CGSizeMake(inWidth, CGFLOAT_MAX), NULL);
CFRelease(framesetter);
return suggestedSize.height;
}
You'll have to convert your NSString to NSAttributedString. In-case of CATextLayer, you can use following CATextLayer subclass method:
- (NSAttributedString *)attributedString {
// If string is an attributed string
if ([self.string isKindOfClass:[NSAttributedString class]]) {
return self.string;
}
// Collect required parameters, and construct an attributed string
NSString *string = self.string;
CGColorRef color = self.foregroundColor;
CTFontRef theFont = self.font;
CTTextAlignment alignment;
if ([self.alignmentMode isEqualToString:kCAAlignmentLeft]) {
alignment = kCTLeftTextAlignment;
} else if ([self.alignmentMode isEqualToString:kCAAlignmentRight]) {
alignment = kCTRightTextAlignment;
} else if ([self.alignmentMode isEqualToString:kCAAlignmentCenter]) {
alignment = kCTCenterTextAlignment;
} else if ([self.alignmentMode isEqualToString:kCAAlignmentJustified]) {
alignment = kCTJustifiedTextAlignment;
} else if ([self.alignmentMode isEqualToString:kCAAlignmentNatural]) {
alignment = kCTNaturalTextAlignment;
}
// Process the information to get an attributed string
CFMutableAttributedStringRef attrString = CFAttributedStringCreateMutable(kCFAllocatorDefault, 0);
if (string != nil)
CFAttributedStringReplaceString (attrString, CFRangeMake(0, 0), (CFStringRef)string);
CFAttributedStringSetAttribute(attrString, CFRangeMake(0, CFAttributedStringGetLength(attrString)), kCTForegroundColorAttributeName, color);
CFAttributedStringSetAttribute(attrString, CFRangeMake(0, CFAttributedStringGetLength(attrString)), kCTFontAttributeName, theFont);
CTParagraphStyleSetting settings[] = {kCTParagraphStyleSpecifierAlignment, sizeof(alignment), &alignment};
CTParagraphStyleRef paragraphStyle = CTParagraphStyleCreate(settings, sizeof(settings) / sizeof(settings[0]));
CFAttributedStringSetAttribute(attrString, CFRangeMake(0, CFAttributedStringGetLength(attrString)), kCTParagraphStyleAttributeName, paragraphStyle);
CFRelease(paragraphStyle);
NSMutableAttributedString *ret = (NSMutableAttributedString *)attrString;
return [ret autorelease];
}
HTH.
I have a much easier solution, that may or may not work for you.
If you aren't doing anything special with the CATextLayer that you can't do a UILabel, instead make a CALayer and add the layer of the UILabel to the CALayer
UILabel*label = [[UILabel alloc]init];
//Do Stuff to label
CALayer *layer = [CALayer layer];
//Set Size/Position
[layer addSublayer:label.layer];
//Do more stuff to layer
With LabelKit you don't need CATextLayer anymore. No more wrong line spacing and wider characters, all is drawn in the same way as UILabel does, while still animated.
This page gave me enough to create a simple centered horizontally CATextLayer : http://lists.apple.com/archives/quartz-dev/2008/Aug/msg00016.html
- (void)drawInContext:(CGContextRef)ctx {
CGFloat height, fontSize;
height = self.bounds.size.height;
fontSize = self.fontSize;
CGContextSaveGState(ctx);
CGContextTranslateCTM(ctx, 0.0, (fontSize-height)/2.0 * -1.0);
[super drawInContext:ctx];
CGContextRestoreGState(ctx);
}

Monotouch - make UIView scrollable

I have a view with 4 text boxes and and a logo at the top - when the user is entering information the text pad covers up some of these controls, how can I make the view scroll so that this isn't an issue.
I have tried adding the view to a UIScrollView but that doesn't seem to do anything?
I've included a snippit below of how I've handled your situation. If I'm understanding you correctly, you do not wish to have a scrollable view, rather you want to the view to move in conjunction with switching to and from fields to alleviate and visual hindrances caused by the keyboard.
Goodluck!
private void ScrollTheView(bool movedUp, float scrollamount, UIView ViewToMove)
{
//To invoke a views built-in animation behaviour,
//you create an animation block and
//set the duration of the move...
//Set the display scroll animation and duration...
UIView.BeginAnimations(string.Empty, System.IntPtr.Zero);
UIView.SetAnimationDuration(0.15);
//Get Display size...
RectangleF frame = ViewToMove.Frame;
if (movedUp) {
//If the view should be moved up,
//subtract the keyboard height from the display...
frame.Y -= scrollamount;
}
else {
//If the view shouldn't be moved up, restore it
//by adding the keyboard height back to the original...
frame.Y += scrollamount;
}
//Assign the new frame to the view...
ViewToMove.Frame = frame;
//Tell the view that your all done with setting
//the animation parameters, and it should
//start the animation...
UIView.CommitAnimations();
}
You need to set more to the UIScrollView than just put subviews in it. Set up the ContentSize property properly for the complete size of the subviews so the scrollview knows about the larger content in it, than you can control the scrolling position, zoom factor and so on.
There are plenty of samples on iOS SDK, just check the UIScrollView documentation, transformation to Monotouch from ObjectiveC is straightforward or check blog post at http://blog.touch4apps.com/home/iphone-monotouch-development/monotouch-infinite-loop-image-scroll-view where I have a sample with images autoscrolled in UIScrollView.
something like this.
textBox.EditingDidBegin += delegate {
var offset = scrollView.contentOffset;
offset.Y -= 200;
scrollView.contentOffset = offset;
}

Resources