How to Fill the Rectangle created by CGRect with Color - swift2

Below code wont paint the CGRect for Rect1,2,3
let context = UIGraphicsGetCurrentContext()
let Rect1 = CGRect(x:30, y:200, width:300, height: 50)
let Rect2 = CGRect(x:30, y:260, width:300, height: 50)
let Rect3 = CGRect(x:30, y:320, width:300, height: 50)
CGContextAddRect(context,Rect1)
CGContextAddRect(context,Rect2)
CGContextAddRect(context,Rect3)
CGContextsetFillColorWithColor(context, UIColor.blueColor().CGColor)
CGContextFillRect(Context,Rect1)
CGContextFillRect(Context,Rect2)
CGContextFillRect(Context,Rect3)
let str1: NSString =" Hello"
let str2: NSString =" How are u?"
let str3: NSString =" See u"
let font = UIFont(name: "Helvetica Neue", size: 18.0)
let textcolor:UIColor = UIColor.whiteColor()
let attr = [NSFontAttributedName:font,
NSForegroundColorAttributedName: textColor]
str1.drawInREct(Rect1, withAttributes: attr)
str2.drawInREct(Rect2, withAttributes: attr)
str3.drawInREct(Rect3, withAttributes: attr)
....
Thanks.

Related

Uitextfield background color blurry?

I am trying to make the background color of a UItextfield blurry. When I try the code below, my app crashes when it runs. Has anyone tried this before and knows how to make a UITextfield blurry?
let p = UITextField()
let blurEffect = UIBlurEffect(style: .light)
let blurView = UIVisualEffectView(effect: blurEffect)
p.layer.isOpaque = true
p.layer.backgroundColor = blurView as! CGColor
I found a solution where you place a view behind the UITextfield, and make it transparent.
let v = UIView()
v.frame = CGRect(x: 30, y: 100, width: 180, height: 30)
let blurEffect = UIBlurEffect(style: .light)
let blurView = UIVisualEffectView(effect: blurEffect)
blurView.frame = v.bounds
blurView.backgroundColor = .clear
v.addSubview(blurView)
let p = UITextField()
p.frame = CGRect(x: 0, y: 0, width: 180, height: 30)
p.layer.isOpaque = true
p.backgroundColor = .clear
v.addSubview(p)
self.view.backgroundColor = .red
self.view.addSubview(v)
This is an example of proposed solution, with background image instead of red color, to emphasize the blur effect
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "background") ?? UIImage())

Views and subviews

I'm trying to put a view with subviews. The view has an image and a text, which are subviews, but when i run the app, it doesn't show the complete text. Here is the codeā€¦
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let ballonview = UIImageView()
let label = UILabel()
let turn = 1
ballonview.frame = CGRectZero
label.frame = CGRectZero
label.backgroundColor = UIColor.clearColor()
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.ByWordWrapping
label.font = label.font.fontWithSize(20)
let message = UIView()
message.frame = CGRectMake(-160, 48, view.frame.size.width, view.frame.size.height)
message.addSubview(ballonview)
message.addSubview(label)
let text: NSString = "hola como estas"
let size:CGSize = text.boundingRectWithSize(CGSizeMake(240.0, 480.0), options: NSStringDrawingOptions.UsesDeviceMetrics, attributes: [NSFontAttributeName: UIFont.systemFontOfSize(14.0)], context: nil).size
var ballon:UIImage = UIImage()
ballonview.frame = CGRectMake(320.0 - (size.width + 28.0), 2.0, size.width + 28.0, size.height + 15.0)
ballon = UIImage(named:"green.png")!.stretchableImageWithLeftCapWidth(24, topCapHeight: 15)
label.frame = CGRectMake(307.0 - (size.width + 5.0), 8.0, size.width + 5.0, size.height)
ballonview.image = ballon;
label.text = text as String
view.addSubview(message)
}
What can I do?
The problem here is that you are using different font sizes when measuring the size and rendering.
The font of label is 20pt system font, and the font you use for measuring size is 14pt system font. So the size will be smaller than you expected.
Also, the drawing options should be changed to NSStringDrawingUsesLineFragmentOrigin in order to get the correct size if you have characters with long legs (like g, j, y).
Reference: official NSString document.
I'd suggest you change the way you measure the size:
let size: CGSize = text.boundingRectWithSize(
CGSizeMake(240.0, 480.0),
options: .UsesLineFragmentOrigin,
attributes: [
NSFontAttributeName: label.font
],
context: nil
).size
So it will match the font you use for rendering the label.
I hope this answer helps you.

how to Horizontal box UIButtons?

I am required to make a view where number of buttons to be displayed will depend upon the argument to init. how can i make it possible horizontal box UIButtons?
override func viewDidLoad() {
var bs = 0;
for index in 1...20
{
bs+=50;var x = CGFloat(bs)
let button = UIButton(type: UIButtonType.System) as UIButton
button.contentMode = UIViewContentMode.ScaleToFill
button.frame = CGRectMake(x, 50, 40, 40) // X, Y, width, height
button.backgroundColor = UIColor.whiteColor()
button.setTitle("12", forState: UIControlState.Normal)
button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
view.addSubview(button);
}
}
i want to like this
You should probably look at UICollectionView
If you don't want to use a UICollectionView, I put up for you this small sample, on which you can try to build on, whether using a UIView or UIScrollView:
let view = UIView(frame: CGRect(origin: CGPointZero, size: CGSize(width: 300, height: 300)))
view.backgroundColor = UIColor.redColor()
let buttonHeight = 40
let buttonWidth = 40
let marginInterCell = 10
let marginInterRow = 20
let numberOfButtonsInRow = 300/(buttonWidth + marginInterCell)
let totalNumberOfButtons = 20
for index in 0..totalNumberOfButtons {
let button = UIButton(type: UIButtonType.System) as UIButton
button.titleLabel?.text = "\(index)"
let x = (index % numberOfButtonsInRow) * (buttonWidth + marginInterCell) + marginInterCell/2
let y = (buttonHeight + marginInterRow) * (index / numberOfButtonsInRow) + marginInterRow/2
button.backgroundColor = UIColor.greenColor()
button.frame = CGRect(origin: CGPoint(x: x, y: y), size: CGSize(width: buttonWidth, height: buttonHeight))
view.addSubview(button)
}

change the color and the font of NStextView

I am trying to change the color and the font size of NSTextView but it doesn't seem to work.This is my code.I have checked other posts but they dont seem to be working.This is my code.
var area:NSRange = NSMakeRange(0, textView.textStorage!.length)
self.textView.setTextColor(NSColor.grayColor(), range: area)
self.textView.textStorage?.font = NSFont(name: "Calibri", size: 16)
You should use attributed strings:
let textView = NSTextView(frame: NSMakeRect(0, 0, 100, 100))
let attributes = [NSForegroundColorAttributeName: NSColor.redColor(),
NSBackgroundColorAttributeName: NSColor.blackColor()]
let attrStr = NSMutableAttributedString(string: "my string", attributes: attributes)
let area = NSMakeRange(0, attrStr.length)
if let font = NSFont(name: "Helvetica Neue Light", size: 16) {
attrStr.addAttribute(NSFontAttributeName, value: font, range: area)
textView.textStorage?.appendAttributedString(attrStr)
}

UiPickerView with custom fixed label and autolayout

I need to implement a UIPickerView to choose hours, minutes and seconds. I need to have a label, next to each component that stay fixed when the picker spin. For example you can look at the timer section of the Apple Clock app. I put an image for reference
of course I need a picker with 3 components but the problem is the same. I found a lot of solution to add a label as a subview and position it using some frames and manual adjustment but a can' t make it work with AutoLayout and i don' t find a solution on the web. Anyone has solved this problem? thanks
Swift 4.2
After create pickerView add next code:
// Fixed labels
let font = UIFont.systemFont(ofSize: 20.0)
let fontSize: CGFloat = font.pointSize
let componentWidth: CGFloat = self.view.frame.width / CGFloat(agePickerView.numberOfComponents)
let y = (agePickerView.frame.size.height / 2) - (fontSize / 2)
let label1 = UILabel(frame: CGRect(x: componentWidth * 0.65, y: y, width: componentWidth * 0.4, height: fontSize))
label1.font = font
label1.textAlignment = .left
label1.text = "Years"
label1.textColor = UIColor.lightGray
agePickerView.addSubview(label1)
let label2 = UILabel(frame: CGRect(x: componentWidth * 1.65, y: y, width: componentWidth * 0.4, height: fontSize))
label2.font = font
label2.textAlignment = .left
label2.text = "Years"
label2.textColor = UIColor.lightGray
agePickerView.addSubview(label2)
let label3 = UILabel(frame: CGRect(x: componentWidth * 0.05, y: 0, width: componentWidth , height: fontSize))
label3.font = font
label3.textAlignment = .center
label3.text = "From"
label3.textColor = UIColor.lightGray
agePickerView.addSubview(label3)
let label4 = UILabel(frame: CGRect(x: componentWidth * 0.95, y: 0, width: componentWidth , height: fontSize))
label4.font = font
label4.textAlignment = .center
label4.text = "To"
label4.textColor = UIColor.lightGray
agePickerView.addSubview(label4)
I thought others could benefit from my additional answer.
For i components, the following should be in your pickerView initialization method (viewDidLoad),
float fontSize = 20;
float labelWidth = self.view.frame.size.width / [self.myPickerView numberOfComponents];
float y = (self.myPickerView.frame.size.height / 2) - (fontSize / 2);
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(labelWidth* i, y, labelWidth, fontSize)];
label.text = #"Label";
label.font = [UIFont boldSystemFontOfSize:fontSize];
label.backgroundColor = [UIColor clearColor];
label.shadowColor = [UIColor whiteColor];
label.shadowOffset = CGSizeMake (0,1);
label.textAlignment = NSTextAlignmentRight;
[self.myPickerView insertSubview:label aboveSubview:[self.myPickerView.subviews objectAtIndex:[self.myPickerView.subviews count] - 1]];
I faced a similar problem in an App I worked on and decided on the following:
i. Create the UIPicker
ii. Find the midpoint of the presented Picker rows.
iii. Add two UILabels to the screen and in - (void)layoutSubview; make sure the labels are always position next to the midpoints.
I only needed portrait mode support in my project, but should work fine for landscape as well. Just choose a wide enough, row width, such that you do not have any overlap with the data inside the picker. Here a snippet of code for the UIPicker:
#pragma mark - Picker View
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 2;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
if(component == 0) {
return self.hourPickerData.count;
} else {
return self.minutePickerData.count;
}
}
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
return 40;
}
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
return 30;
}
-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
NSString *text;
if(component == 0) {
text = self.hourPickerData[row];
} else {
text = self.minutePickerData[row];
}
UILabel *label = (UILabel*)view;
if(view == nil) {
label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 40, 30)];
label.backgroundColor = [UIColor clearColor];
label.text = text;
label.textAlignment = NSTextAlignmentCenter;
label.textColor = LYTiT_HEADER_COLOR;
label.font = [UIFont fontWithName:LT_HELVETICA size:16];
}
return label;
}

Resources