最近很多小伙伴都在问iOS从Swift类/对象重新加载UITableView和swift重新加载当前view这两个问题,那么本篇文章就来给大家详细解答一下,同时本文还将给你拓展iOSSwift,使用标
最近很多小伙伴都在问iOS从Swift类/对象重新加载UITableView和swift重新加载当前view这两个问题,那么本篇文章就来给大家详细解答一下,同时本文还将给你拓展iOS Swift,使用标记在tableview CellForRow之外更新UITableView自定义单元格标签、ios – Swift – UITableView中的标题阻止按钮交互、ios – Swift3:隐藏UITableView如果为空、ios – Swift:删除图层,而不删除UITableViewCell中的UIView等相关知识,下面开始了哦!
本文目录一览:- iOS从Swift类/对象重新加载UITableView(swift重新加载当前view)
- iOS Swift,使用标记在tableview CellForRow之外更新UITableView自定义单元格标签
- ios – Swift – UITableView中的标题阻止按钮交互
- ios – Swift3:隐藏UITableView如果为空
- ios – Swift:删除图层,而不删除UITableViewCell中的UIView
iOS从Swift类/对象重新加载UITableView(swift重新加载当前view)
我正在尝试构建一个面向对象的iOS应用程序,但是从一个我的swift类文件调用表重新加载(ui交互)时遇到了问题。
如果我在没有对象的情况下工作,并在InterfaceController的viewDidLoad方法中编写所有内容,则一切正常…但是如果我将其放入类中则不行。
我正在使用异步请求以便从Web服务加载json数据。接收到数据后,我将这些数据用作表视图的数据源。似乎tableview是在启动后初始化的,没有数据,因此必须在完成异步请求之后在tableview上调用reload()。
因此,这里是详细信息:
主表控制器
import UIKit;class DeviceOverview: UITableViewController {@IBOutlet var myTableView: UITableView!var myDevices = Array<String>();var myDevicesSection = NSMutableDictionary()var deviceObjects = Array<NSDictionary>();var mappingSectionIndex = Array<String>();var sharedUserDefaults = NSUserDefaults(suiteName: "group.barz.fhem.SharingDefaults")// THIS IS AN ATTEMPT TO give the class itself as PARAMETER// ALSO TRIED TO USE myTableView (IBOutlet)var fhem :FHEM = FHEM(tableview : self)override func viewDidLoad() { super.viewDidLoad()}override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return self.fhem.sections.count}override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { var devicesInSection : Array<NSDictionary> = self.fhem.sections[self.fhem.mappingSectionIndex[section]] as! Array<NSDictionary> return devicesInSection.count;}override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("device", forIndexPath: indexPath) as! TableViewCell let sectionName : String = fhem.mappingSectionIndex[indexPath.section] if let devices : Array<NSDictionary> = self.fhem.sections.objectForKey(sectionName) as? Array<NSDictionary> { let device = devices[indexPath.row] var alias : NSString?; if let attr : NSDictionary = device.objectForKey("ATTR") as? NSDictionary { alias = attr.objectForKey("alias") as? String } if (alias != nil) { cell.deviceLabel.text = alias as? String }else{ if let deviceName : String = device.objectForKey("NAME") as? String { cell.deviceLabel.text = deviceName } } } return cell}
FHEM类别
import UIKitclass FHEM: NSObject {var devices : [NSDictionary]var sections : NSMutableDictionaryvar deviceNames : [String]var mappingSectionIndex : [String]var myTableViewController : DeviceOverviewinit(tableview : DeviceOverview){ self.devices = Array<NSDictionary>() self.sections = NSMutableDictionary() self.deviceNames = Array<String>() self.mappingSectionIndex = Array<String>() self.myTableViewController = tableview super.init() let url = NSURL(string: "xyz"); var request = NSURLRequest(URL: url!); NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response, data, error) in if let jsonData: NSData? = data { // do some great stuff // // this is an attempt to call the table view to reload self.myTableViewController.myTableView.reloadData() } }}}
如果我尝试将self
变量放入构造函数的构造函数中,则会引发编译错误
var fhem :FHEM = FHEM(tableview : self)
如果我尝试将UITableView
直接放入构造函数中,它也将不起作用
var fhem :FHEM = FHEM(tableview : myTableView)
我是否在使用对象并与ui交互时走完全错误的道路?
答案1
小编典典您只需在异步任务完成后发布通知:
NSNotificationCenter.defaultCenter().postNotificationName("refreshMyTableView", object: nil)
向该通知添加观察者到您的DeviceOverview类方法viewDidLoad:
NSNotificationCenter.defaultCenter().addObserver(self, selector: "refreshList:", name:"refreshMyTableView", object: nil)
并添加将在您的DeviceOverview类上触发的方法
func refreshList(notification: NSNotification){ myTableView.reloadData()}
iOS Swift,使用标记在tableview CellForRow之外更新UITableView自定义单元格标签
我在UIViewController中有UITableView自定义单元格(标识符= Cell).在自定义TableView单元格中有两个按钮(递增/递减计数)和一个标签(显示计数).
目标:
按下增加计数或减少计数按钮时更新标签.
目前我能够获得按钮Tag并调用CellForRowAtIndexPath之外的函数.按下按钮可增加和减少计数.但我无法在标签中显示计数更新.
func tableView(tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell:FoodTypeTableViewCell = self.tableView!.dequeueReusableCellWithIdentifier("Cell",forIndexPath: indexPath) as! FoodTypeTableViewCell cell.addBtn.tag = indexPath.row // Button 1 cell.addBtn.addTarget(self,action: "addBtn:",forControlEvents: .TouchUpInside) cell.subBtn.tag = indexPath.row // Button 2 cell.subBtn.addTarget(self,action: "subBtn:",forControlEvents: .TouchUpInside) cell.countLabel.text = // How can I update this label return cell } func addBtn(sender: AnyObject) -> Int { let button: UIButton = sender as! UIButton count = 1 + count println(count) return count } func subBtn(sender: AnyObject) -> Int { let button: UIButton = sender as! UIButton if count == 0 { println("Count zero") } else { count = count - 1 } println(count) return count }
我在这里和那里看到过这个问题,但是在Swift中找不到明确的答案.如果您能帮助清楚地回答它,以便其他人不能复制,但清楚地了解正在发生的事情,我将非常感激.
谢谢.
解决方法
使用Swift 2,因为我没有Xcode 6.x了.
让我们从UITableViewCell子类开始.这只是一个标签的哑容器,上面有两个按钮.单元格实际上不执行任何特定的按钮操作,它只是将调用传递给配置方法中提供的闭包.这是MVC的一部分.视图不与模型交互,只与控制器交互.控制器提供闭包.
import UIKit typealias ButtonHandler = (Cell) -> Void class Cell: UITableViewCell { @IBOutlet private var label: UILabel! @IBOutlet private var addButton: UIButton! @IBOutlet private var subtractButton: UIButton! var incrementHandler: ButtonHandler? var decrementHandler: ButtonHandler? func configureWithValue(value: UInt,incrementHandler: ButtonHandler?,decrementHandler: ButtonHandler?) { label.text = String(value) self.incrementHandler = incrementHandler self.decrementHandler = decrementHandler } @IBAction func increment(sender: UIButton) { incrementHandler?(self) } @IBAction func decrement(sender: UIButton) { decrementHandler?(self) } }
现在控制器也很简单
import UIKit class ViewController: UITableViewController { var data: [UInt] = Array(count: 20,repeatedValue: 0) override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view,typically from a nib. } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView,numberOfRowsInSection section: Int) -> Int { return data.count } override func tableView(tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell",forIndexPath: indexPath) as! Cell cell.configureWithValue(data[indexPath.row],incrementHandler: incrementHandler(),decrementHandler: decrementHandler()) return cell } private func incrementHandler() -> ButtonHandler { return { [uNowned self] cell in guard let row = self.tableView.indexPathForCell(cell)?.row else { return } self.data[row] = self.data[row] + UInt(1) self.reloadCellAtRow(row) } } private func decrementHandler() -> ButtonHandler { return { [uNowned self] cell in guard let row = self.tableView.indexPathForCell(cell)?.row where self.data[row] > 0 else { return } self.data[row] = self.data[row] - UInt(1) self.reloadCellAtRow(row) } } private func reloadCellAtRow(row: Int) { let indexPath = NSIndexPath(forRow: row,inSection: 0) tableView.beginUpdates() tableView.reloadRowsAtIndexPaths([indexPath],withRowAnimation: .Automatic) tableView.endUpdates() } }
当单元格出列时,它会使用要在标签中显示的值配置单元格,并提供处理按钮操作的闭包.这些控制器与模型交互,以递增和递减显示的值.更改模型后,它会在tableview中重新加载更改的单元格.
闭包方法采用单个参数,即对单元格的引用,从中可以找到单元格的行.这比使用标签更加去耦合,这对于了解tableview中单元格的索引是非常脆弱的解决方案.
您可以从https://bitbucket.org/abizern/so-32931731/get/ce31699d92a5.zip下载完整的工作示例(需要Xcode7)
ios – Swift – UITableView中的标题阻止按钮交互
Image that shows the buttons before and after (nameOfButton).layer.zPosition = 99
is applied.
即使我的按钮位于标题前面,按钮点按也没有注册…
我正在以编程方式创建按钮,我的viewDidLoad看起来像这样:
override func viewDidLoad() { super.viewDidLoad() // Allow iOS to resize the cells automatically according to our Auto Layout constraints tableView.rowHeight = UITableViewAutomaticDimension // We will take ownership of the header view we've so nicely setup in the storyboard and then remove it from the table view. headerView = tableView.tableHeaderView tableView.tableHeaderView = nil tableView.addSubview(headerView) let addPhotoTapGesture = UITapGestureRecognizer(target: self,action: #selector(ViewController.addPhoto(_:))) headerView.addGestureRecognizer(addPhotoTapGesture) // PhotoPicker createPhotoPickerButtons() let effectiveHeight = kTableHeaderHeight-kTableHeaderCutAway/2 tableView.contentInset = UIEdgeInsets(top: effectiveHeight,left: 0,bottom: 0,right: 0) tableView.contentOffset = CGPoint(x: 0,y: -effectiveHeight) headerMaskLayer = CAShapeLayer() headerMaskLayer.fillColor = UIColor.blackColor().CGColor headerView.layer.mask = headerMaskLayer updateHeaderView() }
还有我的createPhotoPickerButtons()(这里我将按钮放在视图下方,这样我就可以使用showImagePicker()为它们的外观设置动画:
func createPhotoPickerButtons() { takePhotoButton = UIButton.init(type: UIButtonType.System) // .System photoLibraryButton = UIButton.init(type: UIButtonType.System) // .System cancelButton = UIButton.init(type: UIButtonType.System) // .System takePhotoButton.frame = CGRectMake(20,(0 + self.tableView.contentOffset.y + UIScreen.mainScreen().bounds.height),(UIScreen.mainScreen().bounds.width - 40),40) photoLibraryButton.frame = CGRectMake(20,40) cancelButton.frame = CGRectMake(20,40) takePhotoButton.backgroundColor = UIColor(red: 0/255,green: 122/255,blue: 255/255,alpha: 1.0) photoLibraryButton.backgroundColor = UIColor(red: 0/255,alpha: 1.0) cancelButton.backgroundColor = UIColor(red: 0/255,alpha: 1.0) takePhotoButton.setTitle("Take Photo",forState: UIControlState.normal) photoLibraryButton.setTitle("Photo Library",forState: UIControlState.normal) cancelButton.setTitle("Cancel",forState: UIControlState.normal) takePhotoButton.titleLabel?.font = UIFont.systemFontOfSize(17) photoLibraryButton.titleLabel?.font = UIFont.systemFontOfSize(17) cancelButton.titleLabel?.font = UIFont.systemFontOfSize(17) takePhotoButton.setTitleColor(UIColor.whiteColor(),forState: UIControlState.normal) photoLibraryButton.setTitleColor(UIColor.whiteColor(),forState: UIControlState.normal) cancelButton.setTitleColor(UIColor.whiteColor(),forState: UIControlState.normal) let takePhotoButtonTapGesture = UITapGestureRecognizer(target: self,action: #selector(ViewController.takePhotoButtonAction(_:))) takePhotoButton.addGestureRecognizer(takePhotoButtonTapGesture) let photoLibraryButtonTapGesture = UITapGestureRecognizer(target: self,action: #selector(ViewController.photoLibraryButtonAction(_:))) photoLibraryButton.addGestureRecognizer(photoLibraryButtonTapGesture) let cancelButtonTapGesture = UITapGestureRecognizer(target: self,action: #selector(ViewController.cancelButtonAction(_:))) cancelButton.addGestureRecognizer(cancelButtonTapGesture) self.tableView.addSubview(takePhotoButton) self.tableView.addSubview(photoLibraryButton) self.tableView.addSubview(cancelButton) takePhotoButton.layer.zPosition = 99 photoLibraryButton.layer.zPosition = 99 cancelButton.layer.zPosition = 99 takePhotoButton.alpha = 0 photoLibraryButton.alpha = 0 cancelButton.alpha = 0 }
最后我的showImagePicker()在addPhoto()中调用(当用户点击图像时调用的动作):
func showImagePicker(){ // (0 + self.tableView.contentOffset.y + UIScreen.mainScreen().bounds.height - 50 - 10 - 50 - 10 - 50 - 10) UIView.animateWithDuration(0.5) { self.takePhotoButton.alpha = 1 self.photoLibraryButton.alpha = 1 self.cancelButton.alpha = 1 self.takePhotoButton.frame.origin.y = 0 + self.tableView.contentOffset.y + UIScreen.mainScreen().bounds.height - 50 - 10 - 50 - 10 - 50 - 10 self.photoLibraryButton.frame.origin.y = 0 + self.tableView.contentOffset.y + UIScreen.mainScreen().bounds.height - 50 - 10 - 50 - 10 self.cancelButton.frame.origin.y = 0 + self.tableView.contentOffset.y + UIScreen.mainScreen().bounds.height - 50 - 10 } }
我在SO上找不到任何关于这个的东西,也不知道tableView中按钮的另一个解决方案.
解决方法
sectionView.userInteractionEnabled = false
sectionView.layer.zPosition = -1
编辑:SWIFT 3更新:
view.isUserInteractionEnabled = false
ios – Swift3:隐藏UITableView如果为空
@IBOutlet var tableView:UITableView!
有时候我有数据,有时候我没有.
我想只在数据存在时显示表,并在没有数据时隐藏它.
我尝试添加一个高度约束,小于或等于选项.但是,如果我这样做,即使我有数据,tableview也会被隐藏
我该怎么办?
我用Google搜索并没有找到解决方案,所以问这里.
免责声明:我是iOS / Swift开发的新手.对不起,如果已经回答了
解决方法
您可以使用可能用于填充数据的数组或使用tableView属性numberOfRowsInSection来检查计数.
什么时候没有数据
tableView.ishidden = true
什么时候有数据
tableView.ishidden = false
或者您可以使用如下的委托方法.
override func viewWillAppear(_ animated: Bool) { if array.isEmpty { self.tableView.isHidden = true } else { self.tableView.isHidden = false } }
更好的方法是使用didSet.
var dataArray: [String] = [] { didSet { if dataArray.count > 0 { //Update Table Data } else { //Hide Table and show so info of no data } } }
ios – Swift:删除图层,而不删除UITableViewCell中的UIView
我做了一些CABasicAnimation并将它附加到新的CAShapeLayer,然后我将这个图层添加到我的UITableViewCell中的超级图层:
self.layer.addSublayer(myLayer!)
除了myLayer(和他的动画)显示在我的UIView之上之外,一切都很好.
我希望那个标签在UIView下面.
我通过以相同的方式添加我的UIView层来实现这一点:
self.layer.addSublayer(myViewLayer!)
在这种情况下,我的UIView图层位于带有动画的CAShapeLayer的顶部.
但我有一个问题,我需要删除UIView层 – myViewLayer,因为它在滚动时违反了UIView的宽度.
当动画完成后,我需要删除图层,我可以毫无困难地删除CAShapeLayer – myLayer.
myLayer?.removeFromSuperlayer()
但是当我尝试对myViewLayer做同样的事情时,我的UIView也被删除了.但我不希望这样,我需要在屏幕上和我的视图层次结构中使用我的UIView.
我不明白为什么,如果看看self.layer.sublayers我看到这个(在添加图层之前):
[<CALayer: 0x7fd1f0d4fe40>,<CALayer: 0x7fd1f0ddc950>]
完成动画并移除myLayer后:
[<CALayer: 0x7fd1f0d4fe40>,<CALayer: 0x7fd1f0ddc950>,<CAGradientLayer: 0x7fd1f0de3660>]
正如你所看到的,CAGradientLayer是我的UIView层.所以,在我手动将其添加到子图层数组之前,我还没有.我如何删除它,而不删除我的UIView?
或者如何在UIView下面添加myLayer?
编辑
简而言之,我在动画之前有这个图层层次结构:
[<CALayer: 0x7fd1f0d4fe40> <- (I think this is UITableViewCell layer),<CALayer: 0x7fd1f0ddc950> <- (then,this is UITableViewCell content view layer)]
同时,我有这个视图层次结构:
UITableViewCell – >内容视图 – >的UIView
我需要在UIView下面添加带动画的新图层(我希望UIView部分覆盖带动画的新图层).我怎么能这样做?
我在UITableView图层层次结构中没有我的UIView图层,所以我不能只使用addLayer添加带动画的图层:下面:依此类推.
解决方法
当我发现这一点时,我能够修复另一个问题并使用addLayer:下面:
因此,如果您没有看到必须位于对象子层中的图层,则意味着您在错误的位置查看它也可以找到它,就像在UITableView中一样,您需要使用contentView.
关于iOS从Swift类/对象重新加载UITableView和swift重新加载当前view的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于iOS Swift,使用标记在tableview CellForRow之外更新UITableView自定义单元格标签、ios – Swift – UITableView中的标题阻止按钮交互、ios – Swift3:隐藏UITableView如果为空、ios – Swift:删除图层,而不删除UITableViewCell中的UIView等相关知识的信息别忘了在本站进行查找喔。
本文标签: