Issue in using Tabbarcontroller - ios

i am using TabbarController with four tabbarItem. but my requirement is Tabbar is shown in Top on viewController so that is done.but issue is when adding dropdownview on viewcontroller Tabbar hides dropdown. please help me
My viewController Class Code
import UIKit
class TrendingVC: UIViewController,DropDownViewDelegate
{
#IBOutlet var btndropdown: UIButton!
var dropdown = DropDownView()
override func viewDidLoad() {
super.viewDidLoad()
dropdown = dropdown.initWithArrayData(["1111111111","222222222","3233333333","33333333333","1222333333"], cHeight: 30, tableviewHight: 150, tPaddingTop:0, tPaddingLeft: 0, tPaddingRight: 0, refView: btndropdown, tAnimation:AnimationType.GROW, openAnimationDuration: 0.5, closeAnimationDuration: 0.5, Dropdowncolor: UIColor.purpleColor(), DropdowntextColor: UIColor.whiteColor(), DropdowntextSize: 17) as! DropDownView
dropdown.delegate = self;
self.view.addSubview(dropdown.view);
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func DropDownCellSelected(index: NSInteger)
{
print(index);
}
#IBAction func btndropdownclik(sender:UIButton!)
{
self.view.bringSubviewToFront(dropdown.view)
dropdown.OpenAnimation()
}
My Custom Dropdown Class Code Here
import UIKit
enum AnimationType
{
case BLENDIN
case GROW
case BOTH
}
protocol DropDownViewDelegate
{
func DropDownCellSelected(index:NSInteger) -> Void
}
class DropDownView: UIViewController,UITableViewDelegate,UITableViewDataSource
{
var arrDropDown = NSMutableArray()
var delegate: DropDownViewDelegate!
var OPENAnimationDuration,CLOSEAnimationDuration,DropdownViewTextsize,CellHight,DropDownHight,LeftMargin,RightMargin,TopMargin:CGFloat!
var refillview:UIView!
var DropdownViewColor,DropDownviewTextcolor:UIColor!
var animationType:AnimationType!
var tbl:UITableView!
override func viewDidLoad()
{
super.viewDidLoad()
let refFrame:CGRect = refillview.frame;
tbl = UITableView();
tbl.frame = CGRectMake(0, 0, refFrame.size.width+RightMargin, (animationType == AnimationType.BOTH||animationType == AnimationType.BLENDIN) ?DropDownHight:1)
tbl.dataSource = self;
tbl.delegate = self;
//uiTableView.backgroundColor=[UIColor colorWithRed:15/255 green:41/255 blue:63/255 alpha:1];
tbl.backgroundColor = UIColor.clearColor()
self.view.addSubview(tbl)
self.view.hidden = true;
if (animationType == AnimationType.BOTH || animationType == AnimationType.BOTH)
{
self.view.alpha = 1;
}
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Tableview Methods
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrDropDown.count;
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cellidentifier:NSString = "CellId";
var cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier(cellidentifier as String)
if cell==nil
{
cell = UITableViewCell.init(style: UITableViewCellStyle.Default, reuseIdentifier: cellidentifier as String)
}
cell!.backgroundColor = UIColor.purpleColor();
cell!.textLabel?.text = arrDropDown.objectAtIndex(indexPath.row) as? String
cell!.selectionStyle = UITableViewCellSelectionStyle.None;
cell!.textLabel?.font = UIFont(name:"helvetica" , size: 20)
return cell!
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
return CellHight;
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
self.CloseAnimation()
delegate.DropDownCellSelected(indexPath.row)
}
func OpenAnimation()
{
self.view.hidden = false
//var newCenter:CGPoint = CGPointMake(playAgainButton.center.x, playAgainButton.center.y + 200)
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(1.0)
tbl.frame = CGRectMake(tbl.frame.origin.x,tbl.frame.origin.y,tbl.frame.size.width, DropDownHight);
UIView.commitAnimations()
}
func CloseAnimation()
{
self.view.hidden = false;
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(1.0)
tbl.frame = CGRectMake(tbl.frame.origin.x,tbl.frame.origin.y,tbl.frame.size.width, 0);
UIView.commitAnimations()
}
func OpenAnimationWithRef()
{
}
func initWithArrayData(data:NSArray,cHeight:CGFloat,tableviewHight:CGFloat,tPaddingTop:CGFloat,tPaddingLeft:CGFloat,tPaddingRight:CGFloat,refView:UIView!,tAnimation:AnimationType,openAnimationDuration:CGFloat,closeAnimationDuration:CGFloat,Dropdowncolor:UIColor!,DropdowntextColor:UIColor!,DropdowntextSize:CGFloat) -> AnyObject
{
arrDropDown=data.mutableCopy() as! NSMutableArray;
CellHight = cHeight;
DropDownHight = tableviewHight;
TopMargin = tPaddingTop;
LeftMargin = tPaddingLeft;
RightMargin = tPaddingRight;
refillview = refView;
OPENAnimationDuration = openAnimationDuration;
CLOSEAnimationDuration = closeAnimationDuration;
animationType = tAnimation;
DropdownViewColor = Dropdowncolor;
DropDownviewTextcolor = DropdowntextColor;
DropdownViewTextsize = DropdowntextSize;
let reframe = refView.frame;
self.view.frame = CGRectMake(reframe.origin.x-LeftMargin, reframe.origin.y+reframe.size.height+TopMargin, reframe.size.width+RightMargin,DropDownHight);
self.view.layer.shadowColor = UIColor.clearColor().CGColor
self.view.layer.shadowOffset = CGSizeMake(5.0, 5.0)
self.view.layer.shadowOpacity = 1.0;
self.view.layer.shadowRadius = 5.0;
tbl.layer.cornerRadius = 5.0;
tbl.layer.borderWidth = 3.0;
tbl.layer.borderColor = UIColor.darkGrayColor().CGColor;
tbl.autoresizingMask = UIViewAutoresizing.FlexibleWidth;
return self
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}

Related

Mapping between TableView and SearchView

I have a searchController added programatically to my UIViewController on top of my table view. My ViewController handles segues based on rowIndex which poses a problem with my searchview which alters the indices. I have added a mapping array to fix that, but its not working as intended, with out of bounds errors sometimes and it not matching to correct elements. My code below.
import UIKit
class WebpageController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, UISearchResultsUpdating {
var names: [String] = [String]()
var counter = 0
var counter2 = 0
var school: String = String()
var index: Int = Int()
var searchResults: [String] = [String]()
var searchController = UISearchController(searchResultsController: nil)
var searchIndex: [Int] = [Int]()
#IBOutlet var tables: UITableView!
var refreshControl: UIRefreshControl!
override func viewDidLoad() {
super.viewDidLoad()
searchController.searchResultsUpdater = self
searchController.hidesNavigationBarDuringPresentation = false
searchController.dimsBackgroundDuringPresentation = false
searchController.searchBar.sizeToFit()
definesPresentationContext = true
tables.tableHeaderView = searchController.searchBar
names = HtmlController.loadData() as NSArray as! [String]
names.removeAtIndex(0)
clean()
refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(WebpageController.refresh(_:)), forControlEvents: UIControlEvents.ValueChanged)
tables.addSubview(refreshControl)
// Do any additional setup after loading the view.
}
func refresh(sender: AnyObject)
{
names = HtmlController.loadData() as NSArray as! [String]
names.removeAtIndex(0)
clean()
tables.reloadData()
refreshControl.endRefreshing()
}
func updateSearchResultsForSearchController(searchController: UISearchController) {
let searchText = searchController.searchBar.text
filterContentForSearchText(searchText!)
tables.reloadData()
}
func filterContentForSearchText(searchText: String)
{
if(searchText == "")
{
searchResults = names
}
else{
searchResults = names.filter({ ( a: String) -> Bool in
let nameMatch = a.rangeOfString(searchText, options:
NSStringCompareOptions.CaseInsensitiveSearch)
return nameMatch != nil
})
while counter2 < searchResults.count
{
while counter < names.count{
if names[counter] == searchResults[counter2]
{
if searchIndex.count > counter2 && counter > 0
{
searchIndex.removeAtIndex(counter2)
}
searchIndex.insert(counter, atIndex: counter2)
}
counter += 1
}
counter2 += 1
}
}
}
#IBOutlet weak var Table: UITableView!
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func clean()
{
var length = names.count
var i = 0;
var bool = false
let defaults = NSUserDefaults.standardUserDefaults()
if defaults.objectForKey("School") == nil
{
school = "11Staff"
defaults.setObject("11", forKey: "School")
}
else{
school = (defaults.objectForKey("School") as! String) + "Staff"
}
var extra: [String] = [String]()
let bundleidentifier = NSBundle.mainBundle().bundleIdentifier
if let aStreamReader = StreamReader(path: NSBundle.mainBundle().pathForResource(school, ofType: "txt")!)
{
defer {
aStreamReader.close()
}
while let line = aStreamReader.nextLine() {
extra.append(line)
}
}
for String in extra
{
while i < length && bool == false
{
if((String.rangeOfString(names[i].uppercaseString)) != nil)
{
names.removeAtIndex(i)
i -= 1
bool = true
length = names.count
}
i+=1;
}
bool = false
i = 0;
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
if searchController.active
{
return searchResults.count
}
else{
return names.count
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell
if let reusedCell = tableView.dequeueReusableCellWithIdentifier("Cell") {
cell = reusedCell
} else {
cell = UITableViewCell(style: .Default, reuseIdentifier: "Cell")
}
if !searchController.active{
if let label = cell.textLabel {
label.text = names[indexPath.row].uppercaseString
}
}
else{
cell.textLabel!.text = searchResults[indexPath.row].uppercaseString
}
return cell }
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
index = indexPath.row
performSegueWithIdentifier("WebTransfer", sender:self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let Destination: WebsiteController = segue.destinationViewController as! WebsiteController
if !searchController.active
{
Destination.index = index
}
else{
Destination.index = searchIndex[index]
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}

Remove right shadow of UITableViewCell on initial load

I am trying to create a card type layout and have used many answers here to get to my current solution. I am using Swift 2 and XCode 7.3.1.
First App Load
After pull to refresh
The UITableViewCell code is:
func addShadow() {
cardView.layer.shadowPath = UIBezierPath(rect: cardView.bounds).CGPath
cardView.layer.shadowOpacity = 0.7
cardView.layer.shadowOffset = CGSizeZero
cardView.layer.shadowRadius = 2
cardView.layer.masksToBounds = false
}
override func layoutSubviews() {
addShadow()
}
Why does the cell only look correct after a pull to refresh and have the extra shadow to the right beforehand?
EDIT:
I'm added the TableViewController as well
class BusinessTableViewController: PFQueryTableViewController {
override func viewDidLoad() {
super.viewDidLoad()
navigationController!.navigationBar.translucent = false
navigationController?.toolbar.translucent = false
configureTable()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func configureTable() {
tableView.tableFooterView = UIView(frame: CGRectZero)
tableView.backgroundColor = Utility.tableBackgroundColor
}
override func queryForTable() -> PFQuery {
let query = PFQuery(className: "Business")
query.cachePolicy = .NetworkElseCache
query.orderByAscending("createdAt")
return query
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell? {
let cell = tableView.dequeueReusableCellWithIdentifier("businessCell", forIndexPath: indexPath) as! BusinessCell
cell.layoutIfNeeded()
let business = object as! Business
cell.nameLabel.text = business.name
var categoryString = ""
for cat in business.categories {
categoryString += cat
if cat != business.categories.last {
categoryString += ", "
}
}
// Image setup
if cell.mainImageView.layer.cornerRadius != 3 {
cell.mainImageView.layer.cornerRadius = 3
cell.mainImageView.clipsToBounds = true
cell.mainImageView.layer.frame = CGRectInset(cell.mainImageView.layer.frame, 60, 60)
cell.mainImageView.layer.borderColor = UIColor.purpleColor().CGColor
cell.mainImageView.layer.borderWidth = 2.0
}
let imageFile = business.displayImage
cell.mainImageView.file = imageFile
cell.mainImageView.loadInBackground()
// Button steup
let defaultAttributes = [
NSFontAttributeName: UIFont.fontAwesomeOfSize(15),
NSForegroundColorAttributeName: UIColor.grayColor()]
let activeAttributes = [
NSFontAttributeName: UIFont.fontAwesomeOfSize(15),
NSForegroundColorAttributeName: UIColor.blueColor()]
cell.bookmarkButton.setTitleTextAttributes(defaultAttributes, forState: .Normal)
cell.bookmarkButton.title = "\(String.fontAwesomeIconWithName(.BookmarkO)) Bookmark"
let bookmarkQuery = PFQuery(className: "Bookmark")
bookmarkQuery.whereKey("business", equalTo: business)
bookmarkQuery.whereKey("user", equalTo: User.currentUser()!)
bookmarkQuery.cachePolicy = .NetworkElseCache
bookmarkQuery.countObjectsInBackgroundWithBlock { (count, error) in
if error == nil && count > 0 {
cell.bookmarkButton.setTitleTextAttributes(activeAttributes, forState: .Normal)
cell.bookmarkButton.title = "\(String.fontAwesomeIconWithName(.Bookmark)) Bookmark"
}
}
cell.phoneButton.setTitleTextAttributes(defaultAttributes, forState: .Normal)
cell.phoneButton.title = "\(String.fontAwesomeIconWithName(.Phone)) Call"
if business.phone == "" {
cell.phoneButton.enabled = false
}
cell.reviewButton.setTitleTextAttributes(defaultAttributes, forState: .Normal)
cell.reviewButton.title = "\(String.fontAwesomeIconWithName(.MapMarker)) Directions"
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.row + 1 > self.objects?.count {
return 44
}
let height = super.tableView(tableView, heightForRowAtIndexPath: indexPath)
return height
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.row >= self.objects?.count {
self.loadNextPage()
tableView.deselectRowAtIndexPath(indexPath, animated: true)
return
}
//performSegueWithIdentifier("viewBusiness", sender: self)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
I figured this out for anyone who has the same issue:
override func awakeFromNib() {
super.awakeFromNib()
addShadow()
}
I added the code in awakeFromNib instead of layoutSubviews

UITableView is reloaded when presentviewcontroller or pushviewcontroller

I have a uitableview with some complex cells,
If I do presentviewcontroller or pushviewcontroller when I press the button in the cell,
it will reload data automatically,
how can i stop it?
this is the base Controller
import UIKit
class Controller: UIViewController{
override func viewDidLoad() {
super.viewDidLoad();
initView();
}
func initView(){
self.view.backgroundColor = UIColor.whiteColor();
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent;
}
}
and this is the second level
import Foundation
class LoadableController: Controller {
var requestNum : Int = 0;
func loadData(complete: (()->Void)? = nil){
self.requestComplete();
}
func requestComplete(){
if(self.requestNum == 0){
requestFinished();
return;
}
self.requestNum = self.requestNum > 0 ? self.requestNum - 1 : 0;
if(self.requestNum == 0){
requestFinished();
}
}
func requestFinished(){}
}
this is the third level
class TableListViewController: LoadableController, UITableViewDelegate, UITableViewDataSource {
var tableView : UITableView?;
var curPage : Int = 0;
var totalPage : Int = 0;
override func viewDidLoad() {
super.viewDidLoad()
}
override func initView() {
super.initView();
tableView = UITableView();
tableView!.delegate = self;
tableView!.dataSource = self;
tableView!.delaysContentTouches = false;
tableView!.canCancelContentTouches = true;
self.view.addSubview(tableView!);
tableView!.snp_makeConstraints { [unowned self](make) in
make.edges.equalTo(self.view);
}
let header = EGRefresh(refreshingTarget: self, refreshingAction: #selector(self.loadData));
header.setImages(Global.LOADING_IMAGES, duration: 0.16, forState: .Idle);
header.setImages(Global.LOADING_IMAGES, duration: 0.16, forState: .Pulling);
header.setImages(Global.LOADING_IMAGES, duration: 0.16, forState: .WillRefresh);
header.setImages(Global.LOADING_IMAGES, duration: 0.16, forState: .Refreshing);
header.lastUpdatedTimeLabel.hidden = true;
tableView!.mj_header = header;
let footer = MJRefreshBackNormalFooter.init(refreshingTarget: self, refreshingAction: #selector(self.loadNext));
tableView!.mj_footer = footer;
}
func loadNext(){
tableView!.mj_footer.endRefreshing();
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ListCell", forIndexPath: indexPath);
return cell;
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1;
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1;
}
override func requestFinished() {
tableView!.mj_header.endRefreshing();
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
deinit{
DDLogInfo("TableListViewController deinit");
}
}
and here is the place where the tableview reload automatically.
import UIKit
class CircleViewController: TableListViewController {
override func viewDidLoad() {
super.viewDidLoad();
}
override func initView(){
super.initView();
self.title = "Circle";
let items = ["One", "Two"];
let segment = UISegmentedControl(items: items);
segment.selectedSegmentIndex = 0;
segment.setWidth(80, forSegmentAtIndex: 0);
segment.setWidth(80, forSegmentAtIndex: 1);
self.navigationItem.titleView = segment;
tableView!.estimatedRowHeight = 50;
tableView!.rowHeight = UITableViewAutomaticDimension;
// tableView!.contentInset = UIEdgeInsetsMake(Dimens.TopBarHeight, 0, 0, 0);
tableView!.registerClass(TextOnlyCell.self, forCellReuseIdentifier: "CircleTextOnlyCell");
tableView!.registerClass(ImageAndPageCell.self, forCellReuseIdentifier: "CircleImageAndPageCell");
Event.addEventListener(self, selector: #selector(self.goComment(_:)), name: EventType.CIRCLE_COMMENT, object: nil);
}
func goComment(ns: NSNotification) {
let commentView = PostCommentViewController();
self.navigationController?.pushViewController(commentView, animated: true);
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension;
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10;
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true);
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1;
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("CircleImageAndPageCell", forIndexPath: indexPath) as? ImageAndPageCell;
if cell == nil {
cell = ImageAndPageCell.init(style: .Default, reuseIdentifier: "CircleImageAndPageCell");
}
let images = [UIImage(named: "b.jpg")!, UIImage(named: "a.jpg")!, UIImage(named: "c.jpg")!, UIImage(named: "a.jpg")!];
cell?.initView(nil, nickname: "im a nickname", time: "10 min", content: NSMutableAttributedString(string: "asdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdf"), likeNum: 10, commentNum: 12, shareNum: 13, totalLine: 20, images: images, cellIndex: indexPath.row, hasPage: true, pageIcon: UIImage(named: "c.jpg")!, titleStr: "ahahaha");
return cell!;
}
override func loadData(complete: (() -> Void)?) {
self.requestComplete();
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
deinit {
Event.removeAllEventListener(self);
DDLogInfo("CircleViewController deinit");
}
}
If goComment be called,
the viewcontroller will be pushed,
then the tableview will jump to top,
I add a break point to the cellForRowAtIndexPath,
it's called.
then I tried the presentviewcontroller,
this problem also happened,
even though I did presentviewcontroller in the outside viewcontroller.
it seems not reload data,
it's just scrolls to the top.
it's looking like table view not taking the uitoolbar size(44 points) in account
Save the tableview offset in prepareForSegue: (save it in a CGPoint property)
self.tableViewScrollOffset = self.tableView.contentOffset;
Then, in viewWillAppear:, check if it has been modified. If so, restore it.
if(self.tableView.contentOffset.y != self.tableViewScrollOffset.y) {
[self.tableView setContentOffset:self.tableViewScrollOffset];
self.tableViewScrollOffset = CGPointZero;
}

UITableView can't scroll

My UITableView can't scroll, I tried everything I could have possibly done.
Getting a little desperate here.
the tableview implementation here is actually pretty simple, but can't make it work...
Will post the code below:
class RepresentableViewController: DynamicBackgroundViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate {
// MARK: - Properties
var representables: Array<TableCellRepresentable>? {
didSet{
if !self.isAnimatingTable {
self.tableView.reloadData()
}
if self.representables != nil {
self.stopAnimatingIndicator()
}
else {
self.startAnimatingIndicator()
}
}
}
var cellReuseId: String {
return RepresentableTableViewCell.reuseId
}
var isAnimatingTable: Bool = false
private(set) var isSearching: Bool = false
private(set) var searchResults: Array<TableCellRepresentable>? {
didSet {
self.tableView.reloadData()
}
}
var searchResultsCount: Int {
return self.searchResults != nil ? self.searchResults!.count : 0
}
var activeRepresentables: Array<TableCellRepresentable>? {
return self.isSearching ? self.searchResults : self.representables
}
var activeRepresentablesCount: Int {
return self.activeRepresentables != nil ? self.activeRepresentables!.count : 0
}
private(set) var lastSelectedIndex: NSIndexPath?
// MARK: Outlets
#IBOutlet weak var tableView: UITableView!
weak var activityIndicator: UIActivityIndicatorView?
#IBOutlet weak var searchBar: UISearchBar!
// MARK: - Methods
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.setupCell()
self.startAnimatingIndicator()
}
private func setupCell() {
let nib = UINib(nibName: "RepresentableTableViewCell", bundle: nil)
self.tableView.registerNib(nib, forCellReuseIdentifier: RepresentableTableViewCell.reuseId)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if self.representables == nil {
self.postRequestRepresentablesNotification()
}
}
private func postRequestRepresentablesNotification() {
NSNotificationCenter.defaultCenter().postNotificationName(RepresentableViewController.requestRepresentablesNotificationName, object: self, userInfo: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
self.clearRepresentablesIfNotVisible()
}
func insertToTable(item: TableCellRepresentable) {
self.isAnimatingTable = true
if self.representables == nil {
self.self.representables = []
}
self.representables!.append(item)
self.tableView.reloadData()
self.isAnimatingTable = false
}
func removeFromTable(atIndexPath index: NSIndexPath) {
self.isAnimatingTable = true
self.representables!.removeAtIndex(index.row)
self.tableView.deleteRowsAtIndexPaths([index], withRowAnimation: .Automatic)
self.isAnimatingTable = false
}
private func clearRepresentablesIfNotVisible() {
if !self.isViewLoaded() && !(self.view.window != nil) {
self.representables = nil
}
}
private func startAnimatingIndicator() {
if self.activityIndicator == nil {
let indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
indicator.hidesWhenStopped = true
indicator.color = RGBColor(r: 35, g: 131, b: 250, alpha: 1.0)
indicator.center = self.view.center
self.activityIndicator = indicator
self.view.addSubview(indicator)
self.shouldBringToFront?.append(indicator)
indicator.startAnimating()
}
}
private func stopAnimatingIndicator() {
if let indicator = self.activityIndicator {
if let shouldBring = self.shouldBringToFront, index = find(shouldBring, indicator) {
self.shouldBringToFront!.removeAtIndex(index)
}
indicator.stopAnimating()
indicator.removeFromSuperview()
self.activityIndicator = nil
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}*/
// MARK: - Protocols
// MARK: UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.activeRepresentables != nil ? self.activeRepresentables!.count : 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(self.cellReuseId, forIndexPath: indexPath) as! RepresentableTableViewCell
cell.object = self.activeRepresentables![indexPath.row]
return cell
}
// MARK: UITableViewDelegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.lastSelectedIndex = indexPath
NSNotificationCenter.defaultCenter().postNotificationName(RepresentableViewController.didSelectARepresentableNotificationName, object: self, userInfo: [RepresentableViewController.representableKey: self.activeRepresentables![indexPath.row]])
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 60.0
}
// MARK: SearchBarDelegate
private func filterProducts(searchText: String) {
if searchText != "" {
self.searchResults = self.representables?.filter({ (cur: TableCellRepresentable) -> Bool in
let lowerCase: String = searchText.lowercaseString
let titleMatch: Bool = cur.title.lowercaseString.rangeOfString(lowerCase) != nil
let subtitleMatch: Bool = cur.subtitle.lowercaseString.rangeOfString(lowerCase) != nil
let detailMatch: Bool = cur.detail?.lowercaseString.rangeOfString(lowerCase) != nil
return titleMatch || subtitleMatch || detailMatch
})
}
else {
self.searchResults = self.representables
}
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
self.filterProducts(searchText)
}
func searchBarTextDidEndEditing(searchBar: UISearchBar) {
self.isSearching = false
self.searchBar.text = ""
self.searchResults = nil
}
func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
self.isSearching = true
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
searchBar.endEditing(true)
}
// MARK: - Static Properties and Methods
class var didSelectARepresentableNotificationName: String {
return "RepresentableViewController-didSelectARepresentableNotification"
}
class var requestRepresentablesNotificationName: String {
return "RepresentableViewController-RequestRepresentablesNotification"
}
class var representableKey: String {
return "Representable"
}
}
can't figure it out, can someone help me?
thanks.
EDITED
This issue is being caused by a PanGesture at the UITableViewCells, how can I solve this? I still need this pan gesture to move content at the cell.
Fixed with this piece of code at the UITableViewCell
override func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool {
if let panGestureRecognizer = gestureRecognizer as? UIPanGestureRecognizer
{
let translation = panGestureRecognizer.translationInView(superview!)
if fabs(translation.x) > fabs(translation.y)
{
return true
}
return false
}
return false
}

Are there some optional wrong here?

This is the code and the problem
There is no wrong when I did select one row before I add the function tableView(......didSelectRowatindexPath...)
So, I thought it's the root cause.
I hope somebody can help me because the wrong info was not so clear that I can understand it well.
What I want to do is change the BarItemName when I did select one row of my popover table.
SwitchA is a var in my popoverviewcontroller, it means which button is pressed.
When the button in "SecondVC" is pressed,it will pass a value to SwitchA and then the popoverviewcontroller can determine which datasource it should show.
PS:this is the popoverviewcontroller's code.
import UIKit
class PopOverView: UIViewController, UITableViewDataSource, UITableViewDelegate {
var SwitchA = 0
var ClassA = ["这个类型","那个类型","这个类型","那个类型","这个类型","那个类型","这个类型","那个类型","这个类型","那个类型"]
var TimeA = ["昨天","今天","明天","昨天","今天","明天"]
var TagA = ["动漫","音乐","游戏","音乐","游戏"]
#IBOutlet weak var TV: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
TV.dataSource = self
TV.delegate = self
self.preferredContentSize = CGSize(width: UIScreen.mainScreen().bounds.width, height: 175)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
if SwitchA == 0 {
return ClassA.count
}
if SwitchA == 1 {
return TimeA.count
}
else {
return TagA.count
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
if SwitchA == 0 {
let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell
cell.textLabel?.text = ClassA[indexPath.row]
cell.separatorInset = UIEdgeInsetsZero
cell.preservesSuperviewLayoutMargins = false
cell.layoutMargins = UIEdgeInsetsZero
return cell
}
if SwitchA == 1 {
let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell
cell.textLabel?.text = TimeA[indexPath.row]
cell.separatorInset = UIEdgeInsetsZero
cell.preservesSuperviewLayoutMargins = false
cell.layoutMargins = UIEdgeInsetsZero
return cell
}
else {
let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell
cell.textLabel?.text = TagA[indexPath.row]
cell.separatorInset = UIEdgeInsetsZero
cell.preservesSuperviewLayoutMargins = false
cell.layoutMargins = UIEdgeInsetsZero
return cell
}
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 35.0
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: false)
if SwitchA == 0 {
let VC = self.storyboard!.instantiateViewControllerWithIdentifier("SecondVC") as! XiaoNei_HuoDong
VC.ClassName.title = ClassA[indexPath.row]
}
if SwitchA == 1 {
let VC = self.storyboard!.instantiateViewControllerWithIdentifier("SecondVC") as! XiaoNei_HuoDong
VC.TimeName.title = TimeA[indexPath.row]
}
else {
let VC = self.storyboard!.instantiateViewControllerWithIdentifier("SecondVC") as! XiaoNei_HuoDong
VC.TagName.title = TagA[indexPath.row]
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
And this is the code of "SecondVC":
import UIKit
class XiaoNei_HuoDong: UIViewController,UITableViewDelegate,UITableViewDataSource, UIPopoverPresentationControllerDelegate{
#IBOutlet weak var TagName: UIBarButtonItem!
#IBOutlet weak var TimeName: UIBarButtonItem!
#IBOutlet weak var ClassName: UIBarButtonItem!
#IBOutlet weak var huodongTV: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
huodongTV.dataSource = self
huodongTV.delegate = self
huodongTV.showsVerticalScrollIndicator = false
let options = PullToRefreshOption()
options.backgroundColor = UIColor(red: 239/255, green: 239/255, blue: 244/255, alpha: 1)
options.indicatorColor = UIColor.blackColor()
huodongTV.addPullToRefresh(options: options, refreshCompletion: { [weak self] in
// some code
self!.huodongTV.reloadData()
self!.huodongTV.stopPullToRefresh()
})
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return 3
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 1.0
}
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 1.0
}
// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
self.huodongTV.deselectRowAtIndexPath(indexPath, animated: false)
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
if indexPath.row == 0 {
let cell:HuoDong_2 = tableView.dequeueReusableCellWithIdentifier("huodong2") as! HuoDong_2
cell.ClubB1.image = UIImage(named: "test")!
cell.ClubB2.image = UIImage(named: "test")!
cell.ClubS1.image = UIImage(named: "focus")!
cell.ClubS2.image = UIImage(named: "focus")!
cell.Tag1.image = UIImage(named: "更新")!
cell.Tag2.image = UIImage(named: "更新")!
cell.View1.image = UIImage(named: "view")!
cell.View2.image = UIImage(named: "view")!
cell.Newest.image = UIImage(named: "club rank")
return cell
}
else {
let cell:HuoDong = tableView.dequeueReusableCellWithIdentifier("huodong1") as! HuoDong
cell.ClubB1.image = UIImage(named: "test")!
cell.ClubB2.image = UIImage(named: "test")!
cell.ClubS1.image = UIImage(named: "focus")!
cell.ClubS2.image = UIImage(named: "focus")!
cell.Tag1.image = UIImage(named: "更新")!
cell.Tag2.image = UIImage(named: "更新")!
cell.View1.image = UIImage(named: "view")!
cell.View2.image = UIImage(named: "view")!
return cell
}
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath){
cell.layer.transform = CATransform3DMakeScale(0.1, 0.1, 1)
UIView.animateWithDuration(0.25, animations: {
cell.layer.transform = CATransform3DMakeScale(1, 1, 1)
})
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.row == 0 {
return self.view.frame.width * 240.0 / 400.0
}
else {
return self.view.frame.width * 200.0 / 400.0
}
}
// MARK: - PopOverforsegue
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "Class1"{
let VC = segue.destinationViewController as! PopOverView
VC.SwitchA = 0
VC.modalPresentationStyle = UIModalPresentationStyle.Popover
VC.popoverPresentationController?.delegate = self
}
if segue.identifier == "Time1"{
let VC = segue.destinationViewController as! PopOverView
VC.SwitchA = 1
VC.modalPresentationStyle = UIModalPresentationStyle.Popover
VC.popoverPresentationController?.delegate = self
}
if segue.identifier == "Tag1"{
let VC = segue.destinationViewController as! PopOverView
VC.SwitchA = 2
VC.modalPresentationStyle = UIModalPresentationStyle.Popover
VC.popoverPresentationController?.delegate = self
}
}
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
return UIModalPresentationStyle.None
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
I think problem is timing of initialize.
Try this:
SecondVC
var tagNameStr = ""
override func viewDidLoad() {
super.viewDidLoad()
TagName.title = tagNameStr // here
...
}
FirstVC
if SwitchA == 0 {
let VC = self.storyboard!.instantiateViewControllerWithIdentifier("SecondVC") as! XiaoNei_HuoDong
VC.tagNameStr = ClassA[indexPath.row]
}
Hope this helps!
UPDATE
This is sample code.
(ViewController -|segue|-> SecondViewController)
class ViewController: UIViewController {
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let vc = segue.destinationViewController as? SecondViewController {
vc.buttonTitle = "IOhYES"
}
}
}
class SecondViewController: UIViewController {
#IBOutlet weak var buttonItem: UIBarButtonItem!
var buttonTitle = ""
override func viewDidLoad() {
super.viewDidLoad()
buttonItem.title = buttonTitle
}
}
Please check IBOutlet connection.

Resources