Pull down to show view - ios

I have UITableView. I want to add a UITextField above tableView, which could be accessible by pulling tableView down. And I want to hide my textField by pulling tableView up. How can I do this?
Here's what I tried:
[self.messagesTableView addSubview:self.messageField];
- (UITextField*)messageField
{
if (!_messageField)
{
_messageField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, self.messagesTableView.frame.size.width, kMessageFieldHeight)];
_messageField.autoresizingMask = UIViewAutoresizingFlexibleWidth;
_messageField.backgroundColor = [UIColor greenColor];
}
return _messageField;
}
- (void)scrollViewDidScroll:(UIScrollView*)scrollView
{
if (scrollView == self.messagesTableView)
{
CGRect newFrame = self.messagesTableView.frame;
newFrame.origin.y = self.messagesTableView.contentOffset.y + kMessageFieldHeight;
self.messagesTableView.frame = newFrame;
}
}

I have done such kind of functionality in my application. What i did just follow the steps.
1) Add one view to negative position of tableView. Here in this view you can add your textField or button whatever you want as per your requirement.
UIView *viewForSearchBar = [[UIView alloc]initWithFrame:CGRectMake(0, -50, 320, 50)];
viewForSearchBar.backgroundColor = [UIColor clearColor];
[self._tableView addSubview:viewForSearchBar];
self._tableView.contentInset = UIEdgeInsetsMake(50, 0, 0, 0);
2) now when user starts dragging tableview (actual scrollview of table view) you can call scrollview's delegate methods according it to test it.
When you dragging/scrolling tableView down then you will get contentOffset.y will be less then 0, I have explain here in code.
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
if (decelerate) {
[txtSearch resignFirstResponder];
}
id<UILayoutSupport> topLayoutGuide = self.topLayoutGuide;
if(scrollView.contentOffset.y < 0)
{
UIView* hiddenHeader = ...; // this points to the hidden header view above
CGRect headerFrame = [hiddenHeader frame];
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.2];
self._tableView.contentInset = UIEdgeInsetsMake(headerFrame.size.height + [topLayoutGuide length], 0, 0, 0);
[UIView commitAnimations];
} else {
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.2];
self._tableView.contentInset = UIEdgeInsetsMake([topLayoutGuide length], 0, 0, 0);
[UIView commitAnimations];
}
}
This two steps are working fine for me, as i have implemented. Let me add images to verify it.
if you still have any queries you can ask me.

Swift 2.0:
I worked out Nirav's answer in swift Xcode 7.1. Have a look.
let footerView = UIView()
let scroll = UIScrollView()
override func viewDidLoad() {
super.viewDidLoad()
var searchBar:UISearchBar?
searchBar = UISearchBar(frame: CGRectMake(0, 0, 320, 44))
searchBar!.delegate = self
searchBar!.tintColor = UIColor.orangeColor()
footerView.addSubview(searchBar!)
footerView.frame = CGRectMake(0, -50, 320, 50)
footerView.backgroundColor = UIColor.clearColor()
self.listWrapTableView.contentInset = UIEdgeInsetsMake(50, 0, 0, 0);
self.listWrapTableView.addSubview(footerView)
}
Adding scroll method using UIScrollViewDelegate.
func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if(scrollView.contentOffset.y < 0){
print("greater than table height")
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(0.2)
self.listWrapTableView.contentInset = UIEdgeInsetsMake(50, 0, 0, 0)
UIView.commitAnimations()
}
else
{
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(0.2)
self.listWrapTableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0)
UIView.commitAnimations()
}
}

Use UISearchBar instead of UITextField.
And add it as tableView's headerView
Eg:
UISearchBar *mySearchBar = [[UISearchBar alloc] init];
myTableIvew.tableHeaderView = mySearchBar;

Related

UIView appereance from bottom to top and vice versa(Core Animation)

My goal is to understand and implement feature via Core Animation.
I think it's not so hard,but unfortunately i don't know swift/Obj C and it's hard to understand native examples.
Visual implementation
So what exactly i want to do(few steps as shown on images):
1.
2.
3.
4.
And the same steps to hide view(vice versa,from top to bottom) until this :
Also,i want to make this UIView more generic,i mean to put this UIView on my StoryBoard and put so constraints on AutoLayout(to support different device screens).
Any ideas? Thanks!
You can use like this Extension
extension UIView{
func animShow(){
UIView.animate(withDuration: 2, delay: 0, options: [.curveEaseIn],
animations: {
self.center.y -= self.bounds.height
self.layoutIfNeeded()
}, completion: nil)
self.isHidden = false
}
func animHide(){
UIView.animate(withDuration: 2, delay: 0, options: [.curveLinear],
animations: {
self.center.y += self.bounds.height
self.layoutIfNeeded()
}, completion: {(_ completed: Bool) -> Void in
self.isHidden = true
})
}
}
Assuming the original view is something like:
var view = new UIView(new CGRect(View.Frame.Left, View.Frame.Height - 200, View.Frame.Right, 0));
view.BackgroundColor = UIColor.Clear;
Show:
UIView.Animate(2.0, 0.0,
UIViewAnimationOptions.CurveLinear,
() =>
{
view.BackgroundColor = UIColor.Blue;
var height = 100;
view.Frame = new CGRect(View.Frame.Left, view.Frame.Y - height , view.Superview.Frame.Right, height);
},
() =>
{
// anim done
}
);
Hide:
UIView.Animate(2.0, 0.0,
UIViewAnimationOptions.CurveLinear,
() =>
{
view.BackgroundColor = UIColor.Clear;
var height = 100;
view.Frame = new CGRect(View.Frame.Left, view.Frame.Y + height, view.Superview.Frame.Right, 0);
},
() =>
{
view.Hidden = true;
}
);
See my view case was opposite i am directly doing changes in that , test if it is working for you,
Show Logic
//Add your view on storyBoard / programmatically bellow tab bar
[self.view bringSubviewToFront:self.miniMenuView];
CGRect rectformedicationTableViewcell;// = CGRectZero;
rectformedicationTableViewcell = CGRectMake(0.0f, self.view.frame.size.hight, self.view.frame.size.width, 150.0f);
self.miniMenuView.frame = rectformedicationTableViewcell;
if([self.miniMenuView superview]) {
self.miniMenuView.hidden = YES;
}
self.miniMenuView.hidden = NO;
[UIView animateWithDuration:0.3f
delay:0.0f
options:UIViewAnimationOptionBeginFromCurrentState
animations:^{
[self.miniMenuView setFrame:CGRectMake(0.0f, self.view.frame.size.hight - 150.0f, self.view.frame.size.width, 150.0f)];
}
completion:nil];
Hide Logic
[self.view sendSubviewToBack:self.miniMenuView];
[UIView animateWithDuration:0.3f
delay:0.0f
options:UIViewAnimationOptionBeginFromCurrentState
animations:^{
[self.miniMenuView setFrame:CGRectMake(0.0f, self.view.frame.size.hight, self.view.frame.size.width, 150.0f)];
}
completion:^(BOOL completed){
if([self.miniMenuView superview]) {
self.miniMenuView.hidden = YES;
}
}];
Consider this as basic idea do changes as per your requirements Best luck.
Update answer from #SushiHangover in swift 4.x
Assuming the original view is something like:
yourView.frame = CGRect(x: 0, y: 900, width: yourView.frame.width, height: yourView.frame.height)
Show:
UIView.animate(withDuration: 0.5, delay: 0.2, options: .curveLinear, animations: {
let height:CGFloat = 280;
self.yourView.frame = CGRect(x: 0, y: self.yourView.frame.minY - height, width: self.yourView.frame.width, height: self.vBaseView.frame.height)
}) { finished in
// animation done
}
Hide
Just add the height
self.yourView.frame.minY + height
I have also faced the issue like https://i.stack.imgur.com/fuVhy.gif commented https://stackoverflow.com/users/4793465/xtl for the above solution.
Am using the view at the bottom of web-view to show and hide like safari mobile browser.
attached the sample code below
UIView *viewV;
UILabel *label;
and viewdidload
-(void)viewDidLoad {
[super viewDidLoad];
WKWebViewConfiguration *theConfiguration = [[WKWebViewConfiguration alloc] init];
WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:theConfiguration];
webView.navigationDelegate = self;
webView.UIDelegate = self;
webView.scrollView.delegate = self;
NSURL *nsurl=[NSURL URLWithString:#"https://www.google.com/"];
NSURLRequest *nsrequest=[NSURLRequest requestWithURL:nsurl];
[webView loadRequest:nsrequest];
[self.view addSubview:webView];
viewV = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 50, self.view.frame.size.width, 50)];
viewV.backgroundColor = [UIColor blueColor];
[webView addSubview:viewV];}
and scroll view delegate
-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
CGPoint velocity = [[scrollView panGestureRecognizer] velocityInView:scrollView.superview];
if (velocity.y == 0) {
return;
}
if (velocity.y < -1) {
// Scrolling left
NSLog(#"Top");
if (viewV.frame.origin.y != self.view.frame.size.height - 50) {// if already hidden, don't need to hide again
return;
}
[UIView animateWithDuration:0.2 delay:0.0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
viewV.backgroundColor = [UIColor clearColor];
viewV.frame = CGRectMake(0, viewV.frame.origin.y + 50, self.view.frame.size.width, 0);
} completion:^(BOOL finished) {
}];
} else if (velocity.y > 1) {
// Scrolling Right
NSLog(#"Bottom");
if (viewV.frame.origin.y != self.view.frame.size.height) { // if already shown, no need to do show again
return;
}
[UIView animateWithDuration:0.2 delay:0.0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
viewV.backgroundColor = [UIColor blueColor];
viewV.frame = CGRectMake(0, viewV.frame.origin.y - 50, self.view.frame.size.width, 50);
} completion:^(BOOL finished) {
}];
}}
This worked for me.

iOS Floating Video Window like Youtube App

Does anyone know of any existing library, or any techniques on how to get the same effect as is found on the Youtube App.
The video can be "minimised" and hovers at the bottom of the screen - which can then be swiped to close or touched to re-maximised.
See:
Video Playing Normally: https://www.dropbox.com/s/o8c1ntfkkp4pc4q/2014-06-07%2001.19.20.png
Video Minimized: https://www.dropbox.com/s/w0syp3infu21g08/2014-06-07%2001.19.27.png
(Notice how the video is now in a small floating window on the bottom right of the screen).
Anyone have any idea how this was achieved, and if there are any existing tutorials or libraries that can be used to get this same effect?
It sounded fun, so I looked at youtube. The video looks like it plays in a 16:9 box at the top, with a "see also" list below. When user minimizes the video, the player drops to the lower right corner along with the "see also" view. At the same time, that "see also" view fades to transparent.
1) Setup the views like that and created outlets. Here's what it looks like in IB. (Note that the two containers are siblings)
2) Give the video view a swipe up and swipe down gesture recognizer:
#interface ViewController ()
#property (weak, nonatomic) IBOutlet UIView *tallMpContainer;
#property (weak, nonatomic) IBOutlet UIView *mpContainer;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
UISwipeGestureRecognizer *swipeDown = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(swipeDown:)];
UISwipeGestureRecognizer *swipeUp = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(swipeUp:)];
swipeUp.direction = UISwipeGestureRecognizerDirectionUp;
swipeDown.direction = UISwipeGestureRecognizerDirectionDown;
[self.mpContainer addGestureRecognizer:swipeUp];
[self.mpContainer addGestureRecognizer:swipeDown];
}
- (void)swipeDown:(UIGestureRecognizer *)gr {
[self minimizeMp:YES animated:YES];
}
- (void)swipeUp:(UIGestureRecognizer *)gr {
[self minimizeMp:NO animated:YES];
}
3) And then a method to know about the current state, and change the current state.
- (BOOL)mpIsMinimized {
return self.tallMpContainer.frame.origin.y > 0;
}
- (void)minimizeMp:(BOOL)minimized animated:(BOOL)animated {
if ([self mpIsMinimized] == minimized) return;
CGRect tallContainerFrame, containerFrame;
CGFloat tallContainerAlpha;
if (minimized) {
CGFloat mpWidth = 160;
CGFloat mpHeight = 90; // 160:90 == 16:9
CGFloat x = 320-mpWidth;
CGFloat y = self.view.bounds.size.height - mpHeight;
tallContainerFrame = CGRectMake(x, y, 320, self.view.bounds.size.height);
containerFrame = CGRectMake(x, y, mpWidth, mpHeight);
tallContainerAlpha = 0.0;
} else {
tallContainerFrame = self.view.bounds;
containerFrame = CGRectMake(0, 0, 320, 180);
tallContainerAlpha = 1.0;
}
NSTimeInterval duration = (animated)? 0.5 : 0.0;
[UIView animateWithDuration:duration animations:^{
self.tallMpContainer.frame = tallContainerFrame;
self.mpContainer.frame = containerFrame;
self.tallMpContainer.alpha = tallContainerAlpha;
}];
}
I didn't add video to this project, but it should just drop in. Make the mpContainer the parent view of the MPMoviePlayerController's view and it should look pretty cool.
Use TFSwipeShrink and customize code for your project.
hope to help you.
Update new framwork FWDraggableSwipePlayer for drag uiview like YouTube app.
hope to help you.
This is a swift 3 version for the answer #danh had provided earlier.
https://stackoverflow.com/a/24107949/1211470
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var tallMpContainer: UIView!
#IBOutlet weak var mpContainer: UIView!
var swipeDown: UISwipeGestureRecognizer?
var swipeUp: UISwipeGestureRecognizer?
override func viewDidLoad() {
super.viewDidLoad()
swipeDown = UISwipeGestureRecognizer(target: self, action: #selector(swipeDownAction))
swipeUp = UISwipeGestureRecognizer(target: self, action: #selector(swipeUpAction))
swipeDown?.direction = .down
swipeUp?.direction = .up
self.mpContainer.addGestureRecognizer(swipeDown!)
self.mpContainer.addGestureRecognizer(swipeUp!)
}
#objc func swipeDownAction() {
minimizeWindow(minimized: true, animated: true)
}
#objc func swipeUpAction() {
minimizeWindow(minimized: false, animated: true)
}
func isMinimized() -> Bool {
return CGFloat((self.tallMpContainer?.frame.origin.y)!) > CGFloat(20)
}
func minimizeWindow(minimized: Bool, animated: Bool) {
if isMinimized() == minimized {
return
}
var tallContainerFrame: CGRect
var containerFrame: CGRect
var tallContainerAlpha: CGFloat
if minimized == true {
let mpWidth: CGFloat = 160
let mpHeight: CGFloat = 90
let x: CGFloat = 320-mpWidth
let y: CGFloat = self.view.bounds.size.height - mpHeight;
tallContainerFrame = CGRect(x: x, y: y, width: 320, height: self.view.bounds.size.height)
containerFrame = CGRect(x: x, y: y, width: mpWidth, height: mpHeight)
tallContainerAlpha = 0.0
} else {
tallContainerFrame = self.view.bounds
containerFrame = CGRect(x: 0, y: 0, width: 320, height: 180)
tallContainerAlpha = 1.0
}
let duration: TimeInterval = (animated) ? 0.5 : 0.0
UIView.animate(withDuration: duration, animations: {
self.tallMpContainer.frame = tallContainerFrame
self.mpContainer.frame = containerFrame
self.tallMpContainer.alpha = tallContainerAlpha
})
}
}

Padding Placeholder text ios

I want to make the placeholder text display in middle of the textfield (Padding placeholder text). The size of the placeholder text also needs to increase. My code is as follows, how can i solve this ?
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(30, 220,250,55)];
textField.placeholder=#"iiiiiii";
UIView *padView = [[UIView alloc] initWithFrame:CGRectMake(10, 110, 10, 0)];
textField.leftView = padView;
textField.leftViewMode = UITextFieldViewModeAlways;
[self.view addSubview:textField];
UPDATE
I want the font size of the placeholder text to increase your name, and it should have a Left padding to it.
You could subclass your UITextFiled and override methods:
MyTextField.m
- (CGRect)textRectForBounds:(CGRect)bounds {
return [self rectForBounds:bounds];
}
- (CGRect)editingRectForBounds:(CGRect)bounds {
return [self rectForBounds:bounds];
}
- (CGRect)placeholderRectForBounds:(CGRect)bounds {
return [self rectForBounds:bounds];
}
//here 40 - is your x offset
- (CGRect)rectForBounds:(CGRect)bounds {
return CGRectInset(bounds, 40, 3);
}
upd:
also set
textFiled.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
because it could some problems with io6 vs ios 7 vertical positionning
Same question was being asked and answered as below Set padding for UITextField with UITextBorderStyleNone
UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 20)];
textField.leftView = paddingView;
textField.leftViewMode = UITextFieldViewModeAlways;
You can set the starting text alignment (of the textField from xib or via code) to be center aligned.
Then in the -textFieldShouldBeginEditing, you can set the textField to be left aligned.
Similarly, on the -textFieldDidEndEditing, check if the textField is empty and if it is then set textField back to center aligned.
basically:
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
[textField setTextAlignment:NSTextAlignmentLeft];
return YES;
}
-(void)textFieldDidEndEditing:(UITextField *)textField
{
if(textField.text.length == 0) {
[textField setTextAlignment:NSTextAlignmentCenter];
}
}
EDIT::
the .h of your ViewController class should look like:
#interface ViewController : UIViewController <UITextFieldDelegate>
{
UITextField *myTextField;
}
now, replace your other code with this:
myTextField = [[UITextField alloc] initWithFrame:CGRectMake(30, 220,250,55)];
myTextField.placeholder=#"iiiiiii";
//important
[myTextField setDelegate: self];
//commented lines not really needed
//UIView *padView = [[UIView alloc] initWithFrame:CGRectMake(10, 110, 10, 0)];
//textField.leftView = padView;
//textField.leftViewMode = UITextFieldViewModeAlways;
[self.view addSubview:textField];
sampleTextfield.leftView = UIView(frame: CGRectMake(0, 0, 20, self.sampleTextfield.frame.height))
sampleTextfield.leftViewMode = UITextFieldViewMode.Always
The easiest way that I found to do this task on swift 2 and Xcode 7:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var emailTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
let paddingView = UIView(frame: CGRectMake(0, 0, 25, self.emailTextField.frame.height))
emailTextField.leftView = paddingView
emailTextField.leftViewMode = UITextFieldViewMode.Always
}
}
func placeholderPadding(textField:UITextField, leftPadding:CGFloat) {
textField.leftView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: leftPadding, height: textField.frame.height))
textField.leftViewMode = UITextFieldViewMode.always
}
While I have not specifically tested it, this should work:
self.YourTextField.attributedPlaceholder = NSAttributedString(string: " YourText")
Add the amount of blank spaces (padding) to your string

UITextfield leftView/rightView padding on iOS7

The leftView and rightView views of an UITextField on iOS7 are really close to the textfield border.
How may I add some (horizontal) padding to those items?
I tried modifying the frame, but did not work
uint padding = 10;//padding for iOS7
UIImageView * iconImageView = [[UIImageView alloc] initWithImage:iconImage];
iconImageView.frame = CGRectMake(0 + padding, 0, 16, 16);
textField.leftView = iconImageView;
Please, note that I'm not interested in adding padding to the textfield's text, like this Set padding for UITextField with UITextBorderStyleNone
A much simpler solution, which takes advantage of contentMode:
arrow = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"down_arrow"]];
arrow.frame = CGRectMake(0.0, 0.0, arrow.image.size.width+10.0, arrow.image.size.height);
arrow.contentMode = UIViewContentModeCenter;
textField.rightView = arrow;
textField.rightViewMode = UITextFieldViewModeAlways;
In Swift 3,
let arrow = UIImageView(image: UIImage(named: "arrowDrop"))
if let size = arrow.image?.size {
arrow.frame = CGRect(x: 0.0, y: 0.0, width: size.width + 10.0, height: size.height)
}
arrow.contentMode = UIViewContentMode.center
self.textField.rightView = arrow
self.textField.rightViewMode = UITextFieldViewMode.always
Was just working on this myself and used this solution:
- (CGRect) rightViewRectForBounds:(CGRect)bounds {
CGRect textRect = [super rightViewRectForBounds:bounds];
textRect.origin.x -= 10;
return textRect;
}
This will move the image over from the right by 10 instead of having the image squeezed up against the edge in iOS 7.
Additionally, this was in a subclass of UITextField, which can be created by:
Create a new file that's a subclass of UITextField instead of the default NSObject
Add a new method named - (id)initWithCoder:(NSCoder*)coder to set the image
- (id)initWithCoder:(NSCoder*)coder {
self = [super initWithCoder:coder];
if (self) {
self.clipsToBounds = YES;
[self setRightViewMode:UITextFieldViewModeUnlessEditing];
self.leftView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"textfield_edit_icon.png"]];
}
return self;
}
You may have to import #import <QuartzCore/QuartzCore.h>
Add the rightViewRectForBounds method above
In Interface Builder, click on the TextField you would like to subclass and change the class attribute to the name of this new subclass
Easiest way is add a UIView to leftView/righView and add an ImageView to UIView , adjust the origin of ImageView inside UIView anywhere you like , this worked for me like a charm. It needs only few lines of code
UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 5, 26, 26)];
imgView.image = [UIImage imageNamed:#"img.png"];
UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 32, 32)];
[paddingView addSubview:imgView];
[txtField setLeftViewMode:UITextFieldViewModeAlways];
[txtField setLeftView:paddingView];
This works great for Swift:
let imageView = UIImageView(image: UIImage(named: "image.png"))
imageView.contentMode = UIViewContentMode.Center
imageView.frame = CGRectMake(0.0, 0.0, imageView.image!.size.width + 20.0, imageView.image!.size.height)
textField.rightViewMode = UITextFieldViewMode.Always
textField.rightView = imageView
This works for me
UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 20)];
self.passwordTF.leftView = paddingView;
self.passwordTF.leftViewMode = UITextFieldViewModeAlways;
May it helps you.
I like this solution because it solves the problem with a single line of code
myTextField.layer.sublayerTransform = CATransform3DMakeTranslation(10.0f, 0.0f, 0.0f);
Note: .. or 2 if you consider including QuartzCore a line :)
Swift 5
class CustomTextField: UITextField {
func invalidate() {
let errorImage = UIImageView(image: UIImage(named: "errorImage"))
errorImage.frame = CGRect(x: 8, y: 8, width: 16, height: 16)
rightView = UIView(frame: CGRect(x: 0, y: 0, width: 32, height: 32))
rightView?.addSubview(errorImage)
rightViewMode = .always
}
}
You'll want to:
Subclass UITextField
Write an invalidate method inside the
subclassed text field
In the invalidate method, create a UIView
larger than your image
Place your image inside the view
Assign the
view to UITextField.rightView
Instead of manipluating imageView or image we can override a method provided by apple for rightView.
class CustomTextField : UITextField {
override func rightViewRect(forBounds bounds: CGRect) -> CGRect {
let offset = 5
let width = 20
let height = width
let x = Int(bounds.width) - width - offset
let y = offset
let rightViewBounds = CGRect(x: x, y: y, width: width, height: height)
return rightViewBounds
}}
and same way we can override below func for left view.
override func leftViewRect(forBounds bounds: CGRect) -> CGRect {
/*return as per requirement*/
}
The best way to do this is simply make a class using subclass of UITextField and in .m file
#import "CustomTextField.h"
#import <QuartzCore/QuartzCore.h>
#implementation CustomTextField
- (id)initWithCoder:(NSCoder*)coder
{
self = [super initWithCoder:coder];
if (self) {
//self.clipsToBounds = YES;
//[self setRightViewMode:UITextFieldViewModeUnlessEditing];
self.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0,15,46)];
self.leftViewMode=UITextFieldViewModeAlways;
}
return self;
}
by doing this go to your storyboard or xib and click on identity inspector and replace UITextfield with your own "CustomTextField" in class option.
Note: If you simply give padding with auto layout for textfield then your application will not run and show only blank screen.
I found this somewhere...
UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 20)];
paddingView.backgroundColor = [UIColor clearColor];
itemDescription.leftView = paddingView;
itemDescription.leftViewMode = UITextFieldViewModeAlways;
[self addSubview:itemDescription];
Since iOS 13 and Xcode 11 this is the only solution that works for us.
// Init of custom UITextField
override init(frame: CGRect) {
super.init(frame: frame)
if let size = myButton.imageView?.image?.size {
myButton.frame = CGRect(x:0, y: 0, width: size.width, height: size.height)
let padding: CGFloat = 5
let container = UIView(frame: CGRect(x:0, y: 0, width: size.width + padding, height: size.height))
container.addSubview(myButton)
myButton.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
myButton.topAnchor.constraint(equalTo: container.topAnchor),
myButton.leftAnchor.constraint(equalTo: container.leftAnchor),
myButton.bottomAnchor.constraint(equalTo: container.bottomAnchor),
myButton.rightAnchor.constraint(equalTo: container.rightAnchor, constant: -padding),
])
textField.rightViewMode = .always
textField.rightView = container
}
}
Maybe you might set up an empty view and embed your view as a subview:
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 50.0, height: 50.0))
imageView.contentMode = .center
imageView.image = UIImage(named: "ic_dropdown")
let emptyView = UIView(frame: CGRect(x: 0, y: 0, width: 50.0, height: 50.0))
emptyView.backgroundColor = .clear
emptyView.addSubview(imageView)
self.documentTypeTextLabel.rightView = emptyView
self.documentTypeTextLabel.rightViewMode = .always
Happy coding
Create a custom UITextField class and use that class instead of UITextField. Override - (CGRect) textRectForBounds:(CGRect)bounds to set the rect that you need
Example
- (CGRect)textRectForBounds:(CGRect)bounds{
CGRect textRect = [super textRectForBounds:bounds];
textRect.origin.x += 10;
textRect.size.width -= 10;
return textRect;
}
Here is one solution:
UIView *paddingTxtfieldView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 42)]; // what ever you want
txtfield.leftView = paddingTxtfieldView;
txtfield.leftViewMode = UITextFieldViewModeAlways;
Below example is for adding horizontal padding to a left view that happens to be an icon - you can use the similar approach for adding padding to any UIView that you would like to use as the textfield's left view.
Inside UITextField subclass:
static CGFloat const kLeftViewHorizontalPadding = 10.0f;
#implementation TextFieldWithLeftIcon
{
UIImage *_image;
UIImageView *_imageView;
}
- (instancetype)initWithFrame:(CGRect)frame image:(UIImage *)image
{
self = [super initWithFrame:frame];
if (self) {
if (image) {
_image = image;
_imageView = [[UIImageView alloc] initWithImage:image];
_imageView.contentMode = UIViewContentModeCenter;
self.leftViewMode = UITextFieldViewModeAlways;
self.leftView = _imageView;
}
}
return self;
}
#pragma mark - Layout
- (CGRect)leftViewRectForBounds:(CGRect)bounds
{
CGFloat widthWithPadding = _image.size.width + kLeftViewHorizontalPadding * 2.0f;
return CGRectMake(0, 0, widthWithPadding, CGRectGetHeight(bounds));
}
Although we are a subclassing UITextField here, I believe this is the cleanest approach.
- (CGRect)rightViewRectForBounds:(CGRect)bounds
{
return CGRectMake(bounds.size.width - 40, 0, 40, bounds.size.height);
}
thank you guys for your answers, to my surprise none of them really fitted the right view image to my textfield while still providing the needed padding. then i thought of using the AspectFill mode and miracles happened. for future seekers, here's what i used:
UIImageView *emailRightView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 35, 35)];
emailRightView.contentMode = UIViewContentModeScaleAspectFill;
emailRightView.image = [UIImage imageNamed:#"icon_email.png"];
emailTextfield.rightViewMode = UITextFieldViewModeAlways;
emailTextfield.rightView = emailRightView;
the 35 in the frame of my imageview represents the height of my emailTextfield, feel free to adjust it to your needs.
If you are using a UIImageView as leftView then you have to use this code :
Caution : Don't use inside viewWillAppear or viewDidAppear
-(UIView*)paddingViewWithImage:(UIImageView*)imageView andPadding:(float)padding
{
float height = CGRectGetHeight(imageView.frame);
float width = CGRectGetWidth(imageView.frame) + padding;
UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width, height)];
[paddingView addSubview:imageView];
return paddingView;
}
I created a custom method in my ViewController class, like shown bellow:
- (void) modifyTextField:(UITextField *)textField
{
// Prepare the imageView with the required image
uint padding = 10;//padding for iOS7
UIImageView * iconImageView = [[UIImageView alloc] initWithImage:iconImage];
iconImageView.frame = CGRectMake(0 + padding, 0, 16, 16);
// Set the imageView to the left of the given text field.
textField.leftView = iconImageView;
textField.leftViewMode = UITextFieldViewModeAlways;
}
Now I can call that method inside (viewDidLoad method) and send any of my TextFields to that method and add padding for both right and left, and give text and background colors by writing just one line of code, as follows:
[self modifyTextField:self.firstNameTxtFld];
This Worked perfectly on iOS 7! Hope this still works on iOS 8 and 9 too!
I know that adding too much Views might make this a bit heavier object to be loaded. But when concerned about the difficulty in other solutions, I found myself more biased to this method and more flexible with using this way. ;)
Hope this answer might be helpful or useful to figure out another solution to someone else.
Cheers!
This works for me just like I looking for:
func addImageViewInsideMyTextField() {
let someView = UIView(frame: CGRect(x: 0, y: 0, width: 40, height: 24))
let imageView = UIImageView(image: UIImage(named: "accountImage"))
imageView.frame = CGRect(x: 16, y: 0, width: 24, height: 24)
imageView.contentMode = .scaleAspectFit
someView.addSubview(imageView)
self.myTextField.leftView = someView
self.myTextField.leftViewMode = .always
}
Set Rightview of UITextField using swift 4.2
TxtPass.rightViewMode = UITextField.ViewMode.always
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 18, height: 18))
imageView.contentMode = UIView.ContentMode.scaleAspectFit
let image = UIImage(named: "hidepass")
imageView.image = image
let rightView = UIView(frame: CGRect(x: 0, y: 0, width: 28, height: 18))
rightView.addSubview(imageView)
rightView.contentMode = UIView.ContentMode.left
TxtPass.rightView = rightView
One trick: Add a UIView containing UIImageView to UITextField as rightView. This UIView must be larger in size, now place the UIImageView to left of it. So there will be a padding of space from right.
// Add a UIImageView to UIView and now this UIView to UITextField - txtFieldDate
UIView *viewRightIntxtFieldDate = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 30)];
// (Height of UITextField is 30px so height of viewRightIntxtFieldDate = 30px)
UIImageView *imgViewCalendar = [[UIImageView alloc] initWithFrame:CGRectMake(0, 10, 10, 10)];
[imgViewCalendar setImage:[UIImage imageNamed:#"calendar_icon.png"]];
[viewRightIntxtFieldDate addSubview:imgViewCalendar];
txtFieldDate.rightViewMode = UITextFieldViewModeAlways;
txtFieldDate.rightView = viewRightIntxtFieldDate;
I have had this problem myself, and by far the easiest solution is to modify your image to simply add padding to each side of the image!
I just altered my png image to add 10 pixels transparent padding, and it works well, with no coding at all!
Easiest way is just change the Textfield as RoundRect instead of Custom and see the magic. :)
for Swift2 , I use
...
self.mSearchTextField.leftViewMode = UITextFieldViewMode.Always
let searchImg = UIImageView(image: UIImage(named: "search.png"))
let size = self.mSearchTextField.frame.height
searchImg.frame = CGRectMake(0, 0, size,size)
searchImg.contentMode = UIViewContentMode.ScaleAspectFit
self.mSearchTextField.leftView = searchImg
...
...
textField.rightView = UIImageView(image: ...)
textField.rightView?.contentMode = .top
textField.rightView?.bounds.size.height += 10
textField.rightViewMode = .always
...
I realize this an old post and this answer is a bit specific to my use case, but I posted it in case others are seeking a similar solution. I want to move a UITextField's leftView or rightView but I am not putting images in them and do not want any hard coded constants.
My UI calls for hiding the text field's clear button and displaying a UIActivityIndicatorView where the clear button was located.
I add a spinner to the rightView, but out of the box (on iOS 13) it is shifted 20 pixels to the right of the clearButton. I don't like to use magic numbers since the position of the clearButton and rightView are subject to change at any time by Apple. The UI design intent is "spinner where the clear button is" so my solution was to subclass UITextField and override rightViewRect(forBounds).
override func rightViewRect(forBounds bounds: CGRect) -> CGRect {
// Use clearButton's rectangle
return self.clearButtonRect(forBounds: bounds)
}
Below is a working example (sans Storyboard):
//------------------------------------------------------------------------------
class myCustomTextField: UITextField {
override func rightViewRect(forBounds bounds: CGRect) -> CGRect {
// Use clearButton rectangle
return self.clearButtonRect(forBounds: bounds)
}
}
//------------------------------------------------------------------------------
class myViewController: UIViewController {
var activityView: UIActivityIndicatorView = {
let activity = UIActivityIndicatorView()
activity.startAnimating()
return activity
}()
#IBOutlet weak var searchTextField: myCustomTextField!
//------------------------------------------------------------------------------
// MARK: - Lifecycle
//------------------------------------------------------------------------------
override func viewDidLoad() {
super.viewDidLoad()
searchTextField.rightView = activityView
searchTextField.rightViewMode = .never // Hide spinner
searchTextField.clearButtonMode = .never // Hide clear button
setupUIForTextEntry()
}
// ...
// More code to switch between user text entry and "search progress"
// by calling setupUI... functions below
// ...
//------------------------------------------------------------------------------
// MARK: - UI
//------------------------------------------------------------------------------
func setupUIForTextEntry() {
// Hide spinner
searchTextField.rightViewMode = .never
// Show clear button
searchTextField.clearButtonMode = .whileEditing
searchTextField.becomeFirstResponder()
}
//------------------------------------------------------------------------------
func setupUIForSearching() {
// Show spinner
searchTextField.rightViewMode = .always
// Hide clear button
searchTextField.clearButtonMode = .never
searchTextField.resignFirstResponder()
}
//------------------------------------------------------------------------------
}
//------------------------------------------------------------------------------
Simple approach:
textField.rightViewMode = .always
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 25, height: 15))
textField.contentMode = .scaleAspectFit
imageView = UIImage(named: "imageName")
textField.rightView = imageView
Note: Height should be smaller than the width to allow horizontal padding.

How do I add an extra separator to the top of a UITableView?

I have a view for the iPhone that is basically split in two, with an informational display in the top half, and a UITableView for selecting actions in the bottom half. The problem is that there is no border or separator above the first cell in the UITableView, so the first item in the list looks funny. How can I add an extra separator at the top of the table, to separate it from the display area above it?
Here's the code to build the cells - it's pretty straightforward. The overall layout is handled in a xib.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
switch(indexPath.row) {
case 0: {
cell.textLabel.text = #"Action 1";
break;
}
case 1: {
cell.textLabel.text = #"Action 2";
break;
}
// etc.......
}
return cell;
}
To replicate the standard iOS separator lines, I use a 1 px (not 1 pt) hair line tableHeaderView with the table view's separatorColor:
// in -viewDidLoad
self.tableView.tableHeaderView = ({
UIView *line = [[UIView alloc]
initWithFrame:CGRectMake(0, 0,
self.tableView.frame.size.width, 1 / UIScreen.mainScreen.scale)];
line.backgroundColor = self.tableView.separatorColor;
line;
});
The same in Swift (thanks, Dane Jordan, Yuichi Kato, Tony Merritt):
let px = 1 / UIScreen.main.scale
let frame = CGRect(x: 0, y: 0, width: self.tableView.frame.size.width, height: px)
let line = UIView(frame: frame)
self.tableView.tableHeaderView = line
line.backgroundColor = self.tableView.separatorColor
I just got hit with this same problem and realised that the separator at the top is only displayed whilst scrolling the table.
What I then did was the following
In Interface Builder go to "Scroll View Size"
Set the Content Insets of Top to 1
Alternatively in code you could do
[tableView setContentInset:UIEdgeInsetsMake(1.0, 0.0, 0.0, 0.0)];
NOTE: This no longer works for iOS7 as the separators are no longer shown at all.
I had the same problem and could not find an answer. So I added a line to the bottom of my table header.
CGRect tableFrame = [[self view] bounds] ;
CGFloat headerHeight = 100;
UIView * headerView = [[UIView alloc] initWithFrame:CGRectMake(0,0,tableFrame.size.width, headerHeight)];
// Add stuff to my table header...
// Create separator
UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, headerHeight-1, tableFrame.size.width, 1)] ;
lineView.backgroundColor = [UIColor colorWithRed:224/255.0 green:224/255.0 blue:224/255.0 alpha:1.0];
[headerView addSubview:lineView];
self.tableView.tableHeaderView = headerView;
Swift 4
extension UITableView {
func addTableHeaderViewLine() {
self.tableHeaderView = {
let line = UIView(frame: CGRect(x: 0, y: 0, width: self.frame.size.width, height: 1 / UIScreen.main.scale))
line.backgroundColor = self.separatorColor
return line
}()
}
}
I made a UITableView extension that displays a native style separator on top of the UITableView, while the table gets scrolled.
Here's the code
fileprivate var _topSeparatorTag = 5432 // choose unused tag
extension UITableView {
fileprivate var _topSeparator: UIView? {
return superview?.subviews.filter { $0.tag == _topSeparatorTag }.first
}
override open var contentOffset: CGPoint {
didSet {
guard let topSeparator = _topSeparator else { return }
let shouldDisplaySeparator = contentOffset.y > 0
if shouldDisplaySeparator && topSeparator.alpha == 0 {
UIView.animate(withDuration: 0.15, animations: {
topSeparator.alpha = 1
})
} else if !shouldDisplaySeparator && topSeparator.alpha == 1 {
UIView.animate(withDuration: 0.25, animations: {
topSeparator.alpha = 0
})
}
}
}
// Adds a separator to the superview at the top of the table
// This needs the separator insets to be set on the tableView, not the cell itself
func showTopSeparatorWhenScrolled(_ enabled: Bool) {
if enabled {
if _topSeparator == nil {
let topSeparator = UIView()
topSeparator.backgroundColor = separatorColor?.withAlphaComponent(0.85) // because while scrolling, the other separators seem lighter
topSeparator.translatesAutoresizingMaskIntoConstraints = false
superview?.addSubview(topSeparator)
topSeparator.leftAnchor.constraint(equalTo: self.leftAnchor, constant: separatorInset.left).isActive = true
topSeparator.rightAnchor.constraint(equalTo: self.rightAnchor, constant: separatorInset.right).isActive = true
topSeparator.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
let onePixelInPoints = CGFloat(1) / UIScreen.main.scale
topSeparator.heightAnchor.constraint(equalToConstant: onePixelInPoints).isActive = true
topSeparator.tag = _topSeparatorTag
topSeparator.alpha = 0
superview?.setNeedsLayout()
}
} else {
_topSeparator?.removeFromSuperview()
}
}
func removeSeparatorsOfEmptyCells() {
tableFooterView = UIView(frame: .zero)
}
}
To enable it, simply call tableView.showTopSeparatorWhenScrolled(true) after you set your delegate for your UITableView
In complement of Ortwin's answer, if you need to add some margin to your top separator to fit the separator inset, you have to embedded your top separator in another view :
UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 1 / UIScreen.mainScreen.scale)];
UIView *topSeparator = [[UIView alloc] initWithFrame:CGRectMake(self.tableView.separatorInset.left, 0, self.tableView.frame.size.width - self.tableView.separatorInset.left - self.tableView.separatorInset.right, 1 / UIScreen.mainScreen.scale)];
topSeparator.backgroundColor = self.tableView.separatorColor;
[headerView addSubview:topSeparator];
self.tableView.tableHeaderView = headerView;
Hope it helps.
I solved this by adding one extra line at the beginning of the table. Just have to set its height to 1, set its the text to empty, disable user interaction for it and in the whole code adjust the indexPath.row value.
Add a separator between header view and first row :-
In view for Header in section delegate method add a subview self.separator
//#property (nonatomic, strong) UIImageView *separator;
- (CGFloat)tableView:(UITableView *)tableView
heightForHeaderInSection:(NSInteger)section {
return 41;
}
- (UIView *)tableView:(UITableView *)tableView
viewForHeaderInSection:(NSInteger)section {
self.headerView = [[UIView alloc] init];
self.headerView.backgroundColor = [UIUtils colorForRGBColor:TIMESHEET_HEADERVIEW_COLOR];
self.separator = [[UIImageView alloc]initWithImage:[UIImage imageNamed:#"seperator.png"]];
self.separator.frame = CGRectMake(0,40,self.view.frame.size.width,1);
[self.headerView addSubview:self.separator];
return self.headerView;
}

Resources