Unable to load images asynchronous with FSPagerView - ios

I have problem displaying the images in the slider because I have to wait for them to download and then load them inside the FSPagerViewCell ImageView.
Inside the delegate function
- (FSPagerViewCell *)pagerView:(FSPagerView *)pagerView cellForItemAtIndex:(NSInteger)index
I am using an async function which when the image is ready, returns the downloaded image.
I use
dispatch_async(dispatch_get_main_queue(), ^{
to load the image inside the FSPagerViewCell.imageView
but it doesn't show anything, just white space.
Here is the complete code:
- (FSPagerViewCell *)pagerView:(FSPagerView *)pagerView cellForItemAtIndex:(NSInteger)index
{
FSPagerViewCell *cell = [pagerView dequeueReusableCellWithReuseIdentifier:#"pagerCell" atIndex:index];
if (index < [arrMediaGallery count])
{
pageControl.currentPage=index;
MediaGallery *firstImage = arrMediaGallery[index];
NSString *imageName = firstImage.Source;
NSString *imageURL;
if (imageName != nil && [imageName isEqualToString:#"NULL"] == NO && [imageName isEqualToString:#""] == NO) {
imageName = [NSString stringWithFormat:#"thumblarge_%#", imageName];
imageURL = [NSString stringWithFormat:#"%#/cache/photos/%#", [MyApp sharedInstance].settings.StaticURL, imageName];
}
UIImage *image = [NetworkUtilities resolveImageWithName:imageName];
if (image == nil) {
ProcessServerData *processData = [ProcessServerData new];
[processData downloadImageForURL:imageURL verifyDownload:NO
verifyHash:nil
oldImageName:nil
parentView:[cell contentView]
completion:^(NSError *error) {
UIImage* image = [NetworkUtilities resolveImageWithName:[NSString stringWithFormat:#"%#", imageName]];
dispatch_async(dispatch_get_main_queue(), ^{
[UIView transitionWithView:cell.imageView
duration:2.0f
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{
[cell.imageView setImage:image];
} completion:nil];
});
}];
}
else {
[cell.imageView setImage:image];
}
}
return cell;
}
Am I doing something wrong?

Step:1 - install From "https://github.com/WenchaoD/FSPagerView"
Step:2 - import "FSPagerViewDataSource,FSPagerViewDelegate" in VC
Step:3 - implement methods
//MARK: - FSPagerview Delegate and Datasource -
func numberOfItems(in pagerView: FSPagerView) -> Int
{
if pagerView == self.News_images_View
{
return 3
}
else
{
return 3
}
}
func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell
{
let cell = pagerView.dequeueReusableCell(withReuseIdentifier: "cell", at: index)
cell.imageView?.contentMode = .scaleAspectFit
cell.imageView?.clipsToBounds = true
if pagerView == self.News_images_View
{
cell.imageView?.image = UIImage(named: "noticia.jpg")
}
return cell
}
func pagerView(_ pagerView: FSPagerView, didSelectItemAt index: Int)
{
if pagerView == self.News_images_View
{
}
}
#IBOutlet var viewFirstAdvView: FSPagerView!
Inside ViewDidLoad
self.viewFirstAdvView.register(FSPagerViewCell.self, forCellWithReuseIdentifier: "cell") self.viewFirstAdvView.itemSize =
CGSize(width: self.view.frame.size.width, height:
UIScreen.main.bounds.size.width / 2)
self.viewFirstAdvView.isInfinite = true
self.viewFirstAdvView.automaticSlidingInterval = 3.0
self.lastAdvertiseView.transformer =
FSPagerViewTransformer(type:.crossFading)

Related

Custom UITableViewRowAction button

I want to set top and bottom constraint for uitableviewrowaction button
Here's my code
- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:#"Delete" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath){
}];
deleteAction.backgroundColor = [UIColor redColor];
return #[deleteAction];
}
Like this I've added delete button. In tableviewCell I've added one UIView it has top and bottom constraints. I want the delete button to match with my view in UITableviewCell.
you can set delete button frame in your custom uitableviewcell class
like this
-(void)didTransitionToState:(UITableViewCellStateMask)state
{
[super didTransitionToState:state];
if ((state & UITableViewCellStateShowingDeleteConfirmationMask) == UITableViewCellStateShowingDeleteConfirmationMask)
{
UIView *deleteButton = [self deleteButtonSubview:self];
if (deleteButton)
{
CGRect frame = deleteButton.frame;
frame.origin.y = 4;
frame.size.height = frame.size.height-8;
/*
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
frame.size.height = 62; //vikram singh 2/1/2015
frame.size.width = 80;
}
else
{
frame.size.height = 52; //vikram singh 2/1/2015
frame.size.width = 80;
}
*/
deleteButton.frame = frame;
}
}
}
- (UIView *)deleteButtonSubview:(UIView *)view
{
if ([NSStringFromClass([view class]) rangeOfString:#"Delete"].location != NSNotFound) {
return view;
}
for (UIView *subview in view.subviews) {
UIView *deleteButton = [self deleteButtonSubview:subview];
[deleteButton setBackgroundColor:[UIColor whiteColor]];
if (deleteButton) {
return deleteButton;
}
}
return nil;
}
use didTransitionToState methods :)
A little more about Balkaran's answer... The delete button is a custom private class, but using the String(describing:) method, you can be reasonably sure you can get ahold of it.
Also, I was surprised to find that didTransition fires as soon as you start changing the state, not when the state is done changing.
An updated version of #balkaran's code in Swift 3:
override func didTransition(to state: UITableViewCellStateMask) {
super.willTransition(to: state)
if state == .showingDeleteConfirmationMask {
let deleteButton: UIView? = subviews.first(where: { (aView) -> Bool in
return String(describing: aView).contains("Delete")
})
if deleteButton != nil {
deleteButton?.frame.size.height = 50.0
}
super.willTransitionToState(state)
if state == .ShowingDeleteConfirmationMask
{
let deleteButton: UIView? = subviews[0]
if deleteButton != nil {
var frame: CGRect? = deleteButton?.frame
frame?.origin.y = 9
frame?.origin.x = 10
frame?.size.height = (frame?.size.height)! - 14
deleteButton?.frame = frame!
}
}

report an error Ambiguous reference to member 'subviews'

Changes in the table a multiple-choice button style
NSArray *subviews = [[tableView cellForRowAtIndexPath:indexPath] subviews];/* An array of */
for (id subCell in subviews) {
if ([subCell isKindOfClass:[UIControl class]]) {
for (UIImageView *circleImage in [subCell subviews]) {
circleImage.image = [UIImage imageNamed:#"CellButtonSelected"];
}
}
}
/* change */
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) /* table Proxy method */
var subviews = tableView.cellForRowAtIndexPath(indexPath)!.subviews
for subCell: AnyObject in subviews {
if (subCell is UIControl) {
for circleImage: UIImageView in subCell.subviews { /* report an error Ambiguous reference to member 'subviews' */
/* How to solve?*/
circleImage.image = UIImage(named: "CellButtonSelected")!
}
}
}
report an error Ambiguous reference to member 'subviews'
/**Swift, the table of custom boxes, no system, how to change/
Maybe something like this:
for circleImage: UIView in subCell.subviews! {
if let circleImage = circleImage as? UIImageView {
circleImage.image = UIImage(named: "CellButtonSelected")!
}
}
The button click event custom selection button collapsed
for row in 0...self.collectionBookList.count {
let indexPath=NSIndexPath.init(forRow: row, inSection: 0)
self.myTableView.selectRowAtIndexPath(indexPath, animated: false, scrollPosition:.Bottom)
let subviews = self.myTableView.cellForRowAtIndexPath(indexPath)!.subviews
for subCell: AnyObject in subviews {
if (subCell is UIControl) {
for circleImage: UIView in subCell.subviews! {
if let circleImage = circleImage as? UIImageView {
circleImage.image = UIImage(named: "delete")!
}
}
}
}
}

how to add Webview in tableview cell and get dynamic height of cell with webview in ios

hi all I want to add webview in tableview cell , please suggest how to add webview in tablview cell and get dynamic height of tableview cell with web view in ios
Thanks in advance .
It's very important question and After lots of r&d I have implemented that in my code with html code and native string with WKWebview inside UITableviewcell with dynamic height in MVVM architecture.
Please check below code which i have implemented in my code and it's working fine.
I have used xib for cell and Storyboard for tableview.
First I have taken tableview inside storyboard and implemented in my viewcontroller and linked it.
Created tablview cell xib and designed it based on my requirement.
I have taken UItextview for simple text show and WKWebview for show html content.
Here is my viewcontroller code.
import UIKit
class FeedListVC: UIViewController {
// MARK: - Properties
#IBOutlet weak var feedListTblView: UITableView!
private var viewModel = FeedViewModel.shared
// MARK: - Life Cycle
override func viewDidLoad()
{
super.viewDidLoad()
configreTableView()
NotificationCenter.default.addObserver(self, selector: #selector(self.feedHeightUpdateNotification(notification:)), name: Notification.Name(NotificationName.UPDATE_FEED_WEBVIEW_HEIGHT), object: nil)
}
func configreTableView() {
self.viewModel.feedListArr?.removeAll()
feedListTblView.delegate = self
feedListTblView.dataSource = self
feedListTblView.backgroundColor = .white
feedListTblView.separatorStyle = .none
feedListTblView.rowHeight = UITableView.automaticDimension
feedListTblView.estimatedRowHeight = 210
feedListTblView.register(UINib(nibName: NibName.feedListXib, bundle: nil), forCellReuseIdentifier: FeedListTblCell.identifier)
}
// MARK: - Notification Method
#objc func feedHeightUpdateNotification(notification: Notification) {
let notificationData = notification.object as? [String : Any] ?? [:]
let height = notificationData["height"] as? CGFloat ?? 0.0
let index = notificationData["index"] as? Int ?? 0
if let feedArry = self.viewModel.feedListArr, feedArry.count > 0 {
if self.viewModel.feedListArr?[index].webViewHeight ?? 0.0 < 1 {
self.viewModel.feedListArr?[index].webViewHeight = height
reloadFeedTableView()
}
}
}
func reloadFeedTableView() {
DispatchQueue.main.async {
UIView.performWithoutAnimation {
let loc = self.feedListTblView.contentOffset
self.feedListTblView.reloadData()
self.feedListTblView.contentOffset = loc
}
}
}
}
// MARK: - TableView Delegate & DataSource
extension FeedListVC: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.viewModel.feedListArr?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: FeedListTblCell.identifier, for: indexPath) as? FeedListTblCell else { fatalError("xib does not exists") }
cell.selectionStyle = .none
if let item = self.viewModel.feedListArr?[indexPath.row] {
cell.index = indexPath.row
cell.configureCell(feedItem: item)
}
return cell
}
}
My Tableview Cell looks like below.
import UIKit
import WebKit
class FeedListTblCell: UITableViewCell {
// MARK: - Properties
#IBOutlet weak var bgView: UIView!
#IBOutlet weak var topSeparatorLine: UILabel!
#IBOutlet weak var textView: UITextView!
#IBOutlet weak var webView: WKWebView!
#IBOutlet weak var webViewHeightConsraint: NSLayoutConstraint!
class var identifier: String { return String(describing: self) }
var index:Int?
// MARK: - Life Cycle
override func awakeFromNib() {
super.awakeFromNib()
initView()
}
func initView() {
// Cell view customization
backgroundColor = .clear
self.bgView.backgroundColor = .white
}
override func prepareForReuse() {
super.prepareForReuse()
// print("reuse called")
self.bgView.backgroundColor = .clear
self.textView.text = nil
}
func configureCell(feedItem: FeedItem) {
/// Post Text
if let postText = feedItem.postText {
// print("post text ==> \(postText)")
var htmlString = "<html><head><meta name='viewport' content='width=device-width, initial-scale=1'><style type='text/css'> #font-face { font-family: 'Inter-Regular'; src: url('Inter-Regular.ttf'); } p {font-size: 14px !important; font-family: 'Inter-Regular' !important;} b {font-size: 14px !important; font-family: 'Inter-Bold' !important;} span {font-size: 14px !important; font-family: 'Inter-Regular' !important;} strong {font-size: 14px !important; font-family: 'Inter-Regular' !important;} a {font-size: 14px !important; font-family: 'Inter-Regular' !important;} *{background: none}</style></head><body>"
htmlString = htmlString + "\(postText)" + ("</body></html> ")
if htmlString.contains("</math>") {
self.webViewHeightConsraint.constant = feedItem.webViewHeight ?? 0.0
self.webView.uiDelegate = self
self.webView.navigationDelegate = self
self.webView.scrollView.bounces = false
self.webView.scrollView.isScrollEnabled = false
self.webView.backgroundColor = .clear
self.webView.scrollView.backgroundColor = .clear
self.webView.isHidden = false
self.textView.isHidden = true
DispatchQueue.main.async {
self.webView.loadHTMLString(htmlString, baseURL: nil)
}
}else{
self.webViewHeightConsraint.constant = 0.0
self.webView.isHidden = true
self.textView.isHidden = false
self.textView.attributedText = htmlString.htmlToAttributedString
self.richTextView.backgroundColor = .clear
}
}
}
}
extension FeedListTblCell :WKNavigationDelegate, WKUIDelegate {
internal func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
self.webViewHeightConsraint.constant = webView.scrollView.contentSize.height
NotificationCenter.default.post(name: Notification.Name(NotificationName.UPDATE_FEED_WEBVIEW_HEIGHT), object: ["height":webView.scrollView.contentSize.height,"index":self.index!])
}
}
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: #escaping (WKNavigationActionPolicy) -> Void) {
guard case .linkActivated = navigationAction.navigationType,
let url = navigationAction.request.url
else {
decisionHandler(.allow)
return
}
decisionHandler(.cancel)
if UIApplication.shared.canOpenURL(url) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, completionHandler: { (success) in
})
} else {
UIApplication.shared.openURL(url)
}
}
}
}
FeedItem is my model which have webViewHeight key and by-default value is 0.
It's looks like below :
// MARK: - Item
struct FeedItem: Codable {
let postText: String?
var webViewHeight: CGFloat?
enum CodingKeys: String, CodingKey {
case postText = "post_text"
case webViewHeight = "webViewHeight"
}
}
I have used webview for display Math type equations so when first time my tableview load that time inside cell i am checking that it's have math equation then show in webview else display html code in Textview.
First time in webview i am passing height 0 and after load webview i am updating my webview's hight and by using of post notification method i am notifying on my viewcontroller and updating that height on my model item which have in my array with index.
On my viewcontroller i am checking that if webViewHeight is 0 then only update and reload tableview otherwise no need to update because we have already webview's height.
It's working fine and Not creating problem for performance inside tableview.
Thank you
Use the code,
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"ProductsViewCell";
UITableViewCell *cell =
[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
cell =
[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UIWebView* webView = [[UISynchedWebView alloc] initWithFrame:
CGRectMake(0,0, 320, 44)];
webView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
webView.tag = 1001;
webView.userInteractionEnabled = NO;
webView.opaque = NO;
webView.backgroundColor = [UIColor clearColor];
[cell addSubview:webView];
}
UIWebView* webView = (UIWebView*)[cell viewWithTag:1001];
if (isHTML) {
UIFont *font = [UIFont fontWithName:#"Arial" size:15.0f];
NSString *html =
[NSString stringWithFormat:
#"<html>\n"
"<head>\n"
"</head>\n"
"<body><div style=\"padding:5px 0px; text-align:center\"><b>test</b></div></body>\n"
"</html>"];
[webView loadHTMLString:html
baseURL:nil];
webView.hidden = NO;
} else {
cell.textLabel.text = #"Not HTML";
webView.hidden = YES;
}
return cell;
}
If you dynamically change height use the below webView methods,
- (void) webViewDidFinishLoad:(UIWebView *)awebView {
CGRect frame = awebView.frame;
frame.size.height = 1;
awebView.frame = frame;
CGSize fittingSize = [awebView sizeThatFits:CGSizeZero];
frame.size = fittingSize;
awebView.frame = frame;
self.cellSize = fittingSize.height;
[self.tableView beginUpdates];
[self.tableView endUpdates];
NSLog(#"Calling webViewDidFinishLoad. Cell size value: %lf", self.cellSize);
}
hope its helpful
Code for get the height of the cell but not for webview its calculate the height of the cell:
CGSize constraint1 = CGSizeMake(300.0f , CGFLOAT_MAX);
CGRect textRect = [strmessage boundingRectWithSize:constraint1 options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) attributes:#{NSFontAttributeName: [UIFont fontWithName:#"Arial" size:12.0]} context:nil];
CGFloat msgHight = MAX(textRect.size.height,40.0f);
return msgHight

How to use one UIPickerView for two textfields in one view?

I have 2 textfields in one view. I want to populate each using a pickerview. Currently I have succesfully made one picker with one textfield working perfectly but once I edited the code to make it working with two textfield it does not working as expected. Any help will be much appreciated.
Below is my code :
#import "TestPickerVC.h"
#interface TestPickerVC () <UITextFieldDelegate, UIPickerViewDataSource, UIPickerViewDelegate>
{
NSArray *aktivitiArray;
NSArray *penganjurArray;
}
#end
#implementation TestPickerVC
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.penganjurTextField.delegate = self;
self.aktivitiTextField.delegate = self;
aktivitiArray = #[#"apple", #"samsung", #"motorola", #"nokia"];
penganjurArray = #[#"jimbit", #"ayam", #"kambing", #"emergency"];
// self.aktivitiTextField.inputView = self.pickerView1;
// self.penganjurTextField.inputView = self.pickerView2;
self.pickerView = [[UIPickerView alloc] init];
self.pickerView.delegate = self;
self.pickerView.dataSource = self;
self.aktivitiTextField.inputView = self.pickerView;
self.penganjurTextField.inputView = self.pickerView;
self.aktivitiTextField.tag = 1;
self.penganjurTextField.tag = 2;
// if (self.aktivitiTextField.tag == 100) {
// self.aktivitiTextField.inputView = self.pickerView;
// self.pickerView.tag = 1;
// NSLog(#"pickerview tag : %d", (int)self.pickerView.tag);
// } else if (self.penganjurTextField.tag == 200) {
// self.penganjurTextField.inputView = self.pickerView;
// self.pickerView2.tag = 2;
// NSLog(#"pickerview tag : %d", (int)self.pickerView2.tag);
//
// }
}
#pragma mark - UIPickerView DataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
if (self.aktivitiTextField.tag == 1) {
return aktivitiArray.count;
} else if (self.penganjurTextField.tag == 2) {
return penganjurArray.count;
}
return 1;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
if (self.aktivitiTextField.tag == 1) {
return aktivitiArray[row];
} else if (self.penganjurTextField.tag == 2) {
return penganjurArray[row];
}
return #"";
}
#pragma mark - UIPickerView Delegate
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
NSString *selectedAktivitiRow = aktivitiArray[row];
NSString *selectedPenganjurRow = penganjurArray[row];
if (self.aktivitiTextField.tag == 1) {
self.aktivitiTextField.text = selectedAktivitiRow;
} else if (self.penganjurTextField.tag == 2) {
self.penganjurTextField.text = selectedPenganjurRow;
}
}
-(BOOL) textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return YES;
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
#end
Create another private variable as selectedTextField.
#interface TestPickerVC () <UITextFieldDelegate, UIPickerViewDataSource, UIPickerViewDelegate>
{
NSArray *aktivitiArray;
NSArray *penganjurArray;
int selectedTextField
}
The moment you tap on text field, textfield delegate method textFieldDidBeginEditing will be called. In this method, do -
selectedTextField = textField.tag;
Now in picker delegate methods, check with this condition :
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
if (selectedTextField == 1) {
return aktivitiArray.count;
} else if (selectedTextField == 2) {
return penganjurArray.count;
}
return 1;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
if (selectedTextField == 1) {
return aktivitiArray[row];
} else if (selectedTextField == 2) {
return penganjurArray[row];
}
return #"";
}
Do likewise for all picker delegate methods.
You didn't really explain what your issue is but looking at the code there is a pretty glaring issue. Let's look at one method as an example:
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
if (self.aktivitiTextField.tag == 1) {
return aktivitiArray.count;
} else if (self.penganjurTextField.tag == 2) {
return penganjurArray.count;
}
return 1;
}
The problem here is that the first if statement will always be true. Regardless of which text field the picker is for, self.aktivitiTextField.tag == 1 is always true. You have this issue in all of the picker view methods.
You need to check which text field is currently being used. Try the following pattern in all of the picker view methods:
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
if ([self.aktivitiTextField isFirstResponder]) {
return aktivitiArray.count;
} else if ([self.penganjurTextField isFirstResponder]) {
return penganjurArray.count;
}
return 1;
}
Instead you can use .editing for textfields and returns the respective arrays.
Ex:
if (aktivitiTextField.editing) {
return aktivitiArray.count;
} else if (penganjurArray.editing) {
return penganjurArray.count;
}
In swift 3 this is worked for me. Below is the code.
//MARK:- picker view methods
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if (textFieldName .isEqual(to: "firstDoseFld")) {
return arrFirstDose.count
}
else
{
return arrFrequency.count
}
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if (textFieldName .isEqual(to: "firstDoseFld")) {
return arrFirstDose[row]
} else {
return arrFrequency[row]
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if (textFieldName .isEqual(to: "firstDoseFld"))
{
selectedFirstDose = NSString()
selectedFirstDose = arrFirstDose[row] as NSString!
let cell : AddMedicationCell = ordersTable.cellForRow(at: indexPathForCell as IndexPath) as! AddMedicationCell
cell.firstDoseFld.text = selectedFirstDose as String?
} else
{
selectedFrequency = NSString()
selectedFrequency = arrFrequency[row] as NSString!
let cell : AddMedicationCell = ordersTable.cellForRow(at: indexPathForCell as IndexPath) as! AddMedicationCell
cell.frequencyField.text = selectedFrequency as String?
}
}
In textfield delegate method do like this
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool
{
print("textfield is ..\(textField)")
if textField.placeholder == "First Dose"
{
textFieldName = "firstDoseFld"
}
else if textField.placeholder == "Frequency"
{
textFieldName = "frequencyFld"
}
activeTextfield = textField
print(selectedTextField)
return true;
}
In the cellForRowAtIndexPath do like this(set delegate of custom cell textfield) and adding toolbar also here
orderCell.firstDoseFld.delegate = self
orderCell.frequencyField.delegate = self
let toolBar4 = UIToolbar()
toolBar4.barStyle = .default
toolBar4.isTranslucent = true
toolBar4.tintColor = UIColor(red: 92/255, green: 216/255, blue: 255/255, alpha: 1)
toolBar4.sizeToFit()
let doneButtonForFirstDoseFld = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(AddMedicationOrderVC.doneClickedForFirstDoseFld))
let spaceButton4 = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
// let cancelButton = UIBarButtonItem(title: "Cancel", style: .Plain, target: self, action: "cancelClick")
toolBar4.setItems([spaceButton4, doneButtonForFirstDoseFld], animated: false)
toolBar4.isUserInteractionEnabled = true
orderCell.firstDoseFld.inputView = pickerView
orderCell.firstDoseFld.inputAccessoryView = toolBar4
orderCell.firstDoseFld.tintColor = UIColor.clear
Let me know if you need more information. Delare variables based on requirement for this.

How do I make a UITableViewCell appear disabled?

I know about UITableview: How to Disable Selection for Some Rows but Not Others and cell.selectionStyle = UITableViewCellSelectionStyleNone, but how do I make a cell (or any UIView for that matter) appear disabled (grayed-out) like below?
You can just disable the cell's text fields to gray them out:
Swift 4.x
cell!.isUserInteractionEnabled = false
cell!.textLabel!.isEnabled = false
cell!.detailTextLabel!.isEnabled = false
A Swift extension that works well in the context I'm using it; your mileage may vary.
Swift 2.x
extension UITableViewCell {
func enable(on: Bool) {
for view in contentView.subviews as! [UIView] {
view.userInteractionEnabled = on
view.alpha = on ? 1 : 0.5
}
}
}
Swift 3:
extension UITableViewCell {
func enable(on: Bool) {
for view in contentView.subviews {
view.isUserInteractionEnabled = on
view.alpha = on ? 1 : 0.5
}
}
}
Now it's just a matter of calling myCell.enable(truthValue).
Thanks to #Ajay Sharma, I figured out how to make a UITableViewCell appear disabled:
// Mac's native DigitalColor Meter reads exactly {R:143, G:143, B:143}.
cell.textLabel.alpha = 0.439216f; // (1 - alpha) * 255 = 143
aSwitch.enabled = NO; // or [(UISwitch *)cell.accessoryView setEnabled:NO];
And then, to actually disable the cell:
cell.userInteractionEnabled = NO;
Try using a small trick:
Just set the alpha of the cell. Put some condition as your own requirements & set the alpha.
cell.alpha=0.2;
If it does't work,the way you like it to be then, Use second trick,
Just take an image of the cell size having gray background with Transparent Background, just add that image in image over the cell content.
Like this:
// Customize the appearance of table view cells.
- (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];
}
// Configure the cell...
if(indexPath.row==0)
{
cell.userInteractionEnabled=FALSE;
UIImageView *img=[[UIImageView alloc]init];
img.frame=CGRectMake(0, 0, 320, 70);
img.image=[UIImage imageNamed:#"DisableImage.png"];
img.backgroundColor=[UIColor clearColor];
[cell.contentView addSubview:img];
[img release];
}
else {
//Your usual code for cell interaction.
}
return cell;
}
Although I am not not sure about the way,but this will surely fulfill your requirement.This will give a kind of illusion in user's mind that the cell is Disable.
Just try using this solution.Hope that will solve your problem.
Swift 4.X
Nice Extension from Kevin Owens,
I am correcting the behaviour of cell.
extension UITableViewCell {
func enable(on: Bool) {
self.isUserInteractionEnabled = on
for view in contentView.subviews {
self.isUserInteractionEnabled = on
view.alpha = on ? 1 : 0.5
}
}
}
How to call this:-
cell.enable(on: switch.isOn)
Great extension from Kevin Owens, this is my correction to working with Swift 2.x:
extension UITableViewCell {
func enable(on: Bool) {
self.userInteractionEnabled = on
for view in contentView.subviews {
view.userInteractionEnabled = on
view.alpha = on ? 1 : 0.5
}
}
}
Swift 3:
extension UITableViewCell {
func enable(on: Bool) {
self.isUserInteractionEnabled = on
for view in contentView.subviews {
view.isUserInteractionEnabled = on
view.alpha = on ? 1 : 0.5
}
}
}
I have created following extension to Enable/Disable UITableViewCell, it is very convenient to use it.
Create UITableViewCell Extension with "UITableViewCell+Ext.h" contain following in it.
#interface UITableViewCell (Ext)
- (void)enableCell:(BOOL)enabled withText:(BOOL)text;
- (void)enableCell:(BOOL)enabled withText:(BOOL)text withDisclosureIndicator:(BOOL)disclosureIndicator;
- (void)disclosureIndicator:(BOOL)disclosureIndicator;
#end
"UITableViewCell+Ext.m" contain following in it.
#implementation UITableViewCell (Ext)
- (UITableView *)uiTableView {
if ([[UIDevice currentDevice] systemVersionIsGreaterThanOrEqualTo:#"7.0"]) {
return (UITableView *)self.superview.superview;
}
else {
return (UITableView *)self.superview;
}
}
- (void)enableCell:(BOOL)enabled withText:(BOOL)text {
if (enabled) {
self.userInteractionEnabled = YES;
if (text) {
self.textLabel.alpha = 1.0f;
self.alpha = 1.0f;
self.detailTextLabel.hidden = NO;
}
}
else {
self.userInteractionEnabled = NO;
if (text) {
self.textLabel.alpha = 0.5f;
self.alpha = 0.5f;
self.detailTextLabel.hidden = YES;
}
}
}
- (void)enableCell:(BOOL)enabled withText:(BOOL)text withDisclosureIndicator:(BOOL)disclosureIndicator {
if (enabled) {
self.userInteractionEnabled = YES;
if (text) {
self.textLabel.alpha = 1.0f;
self.alpha = 1.0f;
self.detailTextLabel.hidden = NO;
}
self.accessoryType = disclosureIndicator ? UITableViewCellAccessoryDisclosureIndicator : UITableViewCellAccessoryNone;
}
else {
self.userInteractionEnabled = NO;
if (text) {
self.textLabel.alpha = 0.5f;
self.alpha = 0.5f;
self.detailTextLabel.hidden = YES;
}
self.accessoryType = UITableViewCellAccessoryNone;
}
}
- (void)disclosureIndicator:(BOOL)disclosureIndicator {
if (disclosureIndicator) {
self.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
else {
self.accessoryType = UITableViewCellAccessoryNone;
}
}
#end
How to Disable Cell:
[cell enableCell:NO withText:NO];
[cell enableCell:NO withText:YES withDisclosureIndicator:YES];
How to Enable Cell:
[cell enableCell:YES withText:NO];
[cell enableCell:YES withText:YES withDisclosureIndicator:YES];
Hope it helps you.
for swift
cell.isUserInteractionEnabled = false
Swift 5 version
class CustomCell: UITableViewCell {
private func isEnabled(_ enabled: Bool) {
isUserInteractionEnabled = enabled
subviews.forEach { subview in
subview.isUserInteractionEnabled = enabled
subview.alpha = enabled ? 1 : 0.5
}
}
}

Resources