ios swift 中未选择段控制
segmentcontrol is not selecting in ios swift
我在项目中使用了段控制。在其选择中,我正在显示我的 table 视图数据,但在加载后没有显示任何内容,但在按下按钮后显示所有数据。所以问题是默认情况下选择了我的段控件,但数据未填充 table 视图。尽管如此,我还是使用了段控制选择的方法
//ViewController
import UIKit
class MyOrdersVC: UIViewController {
//MARK: - IBOutlets
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var segmentedControl: UISegmentedControl!
//MARK: - Variables
var searchController = UISearchController()
// list all pagerlist
var totalOrders = [BookingMasterModel]() {
didSet {
tableView.reloadData()
}
}
var upcomingOrders = [BookingMasterModel]() {
didSet {
tableView.reloadData()
}
}
var completedOrders = [BookingMasterModel]() {
didSet {
tableView.reloadData()
}
}
var cancelledOrders = [BookingMasterModel]() {
didSet {
tableView.reloadData()
}
}
var arrFilter:[BookingMasterModel] = [] {
didSet{
tableView.reloadData()
}
}
//MARK: ViewController Life cycle
override func viewDidLoad() {
super.viewDidLoad()
// index = 0
segmentedControl.selectedSegmentIndex = 0
segmentedControl.setEnabled(true, forSegmentAt: 0)
segmentedControl.sendActions(for: .valueChanged)
//searchbar configuration
configureSearchController()
//By default Upcoming order is selected
callUpdatedOrders(totalOrders: totalOrders)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(false)
segmentedControl.selectedSegmentIndex = 0
callMyOrders()
}
//configure SearchViewController
func configureSearchController() {
self.searchController = ({
let controller = UISearchController(searchResultsController: nil)
controller.searchResultsUpdater = self
controller.dimsBackgroundDuringPresentation = true
controller.searchBar.sizeToFit()
controller.searchBar.placeholder = "Search by Receipt No, Order No"
controller.searchBar.showsCancelButton = false
controller.searchBar.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
controller.searchBar.searchBarStyle = .minimal
controller.searchBar.setShowsCancelButton(false, animated: false)
let textFieldInsideSearchBar = controller.searchBar.value(forKey: "searchField") as? UITextField
let imageView = textFieldInsideSearchBar?.leftView as! UIImageView
imageView.image = imageView.image?.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
imageView.tintColor = #colorLiteral(red: 0.8901960784, green: 0.1764705882, blue: 0.2156862745, alpha: 1)
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
imageView.isUserInteractionEnabled = true
imageView.addGestureRecognizer(tapGestureRecognizer)
//Add searchbar controller in header
self.tableView.tableHeaderView = controller.searchBar
return controller
})()
}
@objc func imageTapped(tapGestureRecognizer: UITapGestureRecognizer)
{
let tappedImage = tapGestureRecognizer.view as! UIImageView
print("Image tapped red")
// Your action
}
//MARK: - Button Action
@IBAction func segmentedControlAction(_ sender: Any) {
switch segmentedControl.selectedSegmentIndex {
case 0:
print("1")
callUpdatedOrders(totalOrders: totalOrders)
break
case 1:
print("2")
callCompletedOrders(totalOrders: totalOrders)
// tableView.reloadData()
// selectionFlag = 1
break
case 2:
print("3")
callCancelledOrders(totalOrders: totalOrders)
// tableView.reloadData()
// selectionFlag = 2
break
default:
print("Select proper segment")
callUpdatedOrders(totalOrders: totalOrders)
break
}
}
//MARK: - Arrays
func callUpdatedOrders(totalOrders : [BookingMasterModel]) {
upcomingOrders = totalOrders
upcomingOrders = upcomingOrders.filter { ([=12=].status != "CANCELLED") || [=12=].status != "REJECTED" || [=12=].status != "SERVICED" || [=12=].status != "DONE" || [=12=].status != "CREDITED" || [=12=].status != "DILEVERY" || [=12=].status != "REPORTED" || [=12=].status != "PARTIALY DONE" || [=12=].status != "DISPATCHED"}
}
func callCompletedOrders(totalOrders : [BookingMasterModel]) {
completedOrders = totalOrders
completedOrders = completedOrders.filter { [=12=].status == "SERVICED" || [=12=].status == "DONE" || [=12=].status == "CREDITED" || [=12=].status == "DILEVERY" || [=12=].status == "REPORTED" || [=12=].status == "PARTIALY DONE" || [=12=].status == "DISPATCHED" }
}
func callCancelledOrders(totalOrders : [BookingMasterModel]) {
cancelledOrders = totalOrders
cancelledOrders = cancelledOrders.filter { [=12=].status == "CANCELLED" || [=12=].status == "REJECTED" }
}
//MARK : - Webservices
//MARK: View Profile
func callMyOrders(){
let url = Utilities.stringToUrl(urlString: finalUrl)
WebService.requestServices(url: url, method: .get, parameters: [:], view: view, showLoaderFlag: true) { (json) in
let orderObj = MyOrderModels(fromJson: json)
guard let success = orderObj.response else {
return
}
if success == "SUCCESS" {
if let details = orderObj.bookingMasterModels {
for value in details {
self.totalOrders.append(value)
}
print("Total Orders:- \(self.totalOrders.count)")
}
self.tableView.reloadData()
}
}
}
}
extension MyOrdersVC : TableViewDelegateGroup {
//MARK: UITableViewDelegate
private func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
}
private func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 44
}
//MARK: UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//TODO: Switch
switch segmentedControl.selectedSegmentIndex {
case 0:
return searchController.isActive ? arrFilter.count : upcomingOrders.count
case 1:
return searchController.isActive ? arrFilter.count : completedOrders.count
case 2:
return searchController.isActive ? arrFilter.count : cancelledOrders.count
default:
break
}
return searchController.isActive ? arrFilter.count : upcomingOrders.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier:
MyOrdersTableViewCell.identifier, for: indexPath) as? MyOrdersTableViewCell{
//TODO: Switch
var order: BookingMasterModel?
switch segmentedControl.selectedSegmentIndex {
case 0:
order = searchController.isActive ? arrFilter[indexPath.row] : upcomingOrders[indexPath.row]
case 1:
order = searchController.isActive ? arrFilter[indexPath.row] : completedOrders[indexPath.row]
case 2:
order = searchController.isActive ? arrFilter[indexPath.row] : cancelledOrders[indexPath.row]
default:
order = searchController.isActive ? arrFilter[indexPath.row] : upcomingOrders[indexPath.row]
}
cell.orderDetails = order
cell.setOrders()
//Logic to display color background
var count : Int = 0
//suppose indexpath count exceeds to colorarray count then count = 32 /31 = 1 .... 2...
count = indexPath.row / colorArray.count
var x: Int = 0
x = indexPath.row - (count) * colorArray.count
cell.backgroundColor = colorArray[x]
return cell
}
return UITableViewCell()
}
}
extension MyOrdersVC : UISearchResultsUpdating,UISearchBarDelegate{
func updateSearchResults(for searchController: UISearchController) {
let searchText = searchController.searchBar.text ?? ""
switch segmentedControl.selectedSegmentIndex {
case 0:
arrFilter = upcomingOrders.filter { order in
let isMatchingSearchText = order.names.lowercased().contains(searchText.lowercased()) || searchText.lowercased().count == 0
return isMatchingSearchText
}
case 1:
arrFilter = completedOrders.filter { order in
let isMatchingSearchText = order.names.lowercased().contains(searchText.lowercased()) || searchText.lowercased().count == 0
return isMatchingSearchText
}
case 2:
arrFilter = cancelledOrders.filter { order in
let isMatchingSearchText = order.names.lowercased().contains(searchText.lowercased()) || searchText.lowercased().count == 0
return isMatchingSearchText
}
default:
break
}
}
private func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
searchBar.setShowsCancelButton(false, animated: false)
}
private func searchBarTextDidEndEditing(searchBar: UISearchBar) {
searchBar.setShowsCancelButton(false, animated: false)
}
}
在cell里面,我在做这个操作
import UIKit
class MyOrdersTableViewCell: UITableViewCell {
//MARK: IBOutlets
@IBOutlet weak var orderNo: UILabel!
@IBOutlet weak var apptDateLabel: UILabel!
//MARK: Variables
var orderDetails:BookingMasterModel?{
didSet{
setOrders()
}
}
class var identifier: String {
return String(describing: self)
}
class var nib: UINib {
return UINib(nibName: identifier, bundle: nil)
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
//MARK: Extra Function
//*******************
// function call when set ordres cell called
func setOrders(){
guard let txt = orderDetails?.names else {return}
self.orderNo.text = txt
}
}
问题是您在 UISegmentedControl
的操作中调用 callUpdatedOrders(totalOrders: totalOrders)
时您没有任何 totalOrders 因为您还没有数据。因此,如果您想在 ViewController
出现时显示数据,请调用 callMyOrders()
方法,并在此方法中在将订单附加到 totalOrders
[=26 后立即调用 callUpdatedOrders(totalOrders: totalOrders)
=]
if let details = orderObj.bookingMasterModels {
for value in details {
self.totalOrders.append(value)
}
print("Total Orders:- \(self.totalOrders.count)")
}
self.callUpdatedOrders(totalOrders: totalOrders)
备注:
- 您不必使用参数
totalOrders
调用函数 callUpdatedOrders
, ... 因为 totalOrders
是全局变量
- 对于
viewDidLoad
中的情况,您应该只调用 super.viewDidLoad()
和 configureSearchController()
- 在
callMyOrders()
的末尾你不必调用 self.tableView.reloadData()
这是当你设置 upcomingOrders
的值时调用
实际上,当您第一次在段控件中调用 callUpdateOrders 时,它不会在 updatingArray 中获取数据。所以按照罗伯特的建议在呼叫订单中称呼它。
我在项目中使用了段控制。在其选择中,我正在显示我的 table 视图数据,但在加载后没有显示任何内容,但在按下按钮后显示所有数据。所以问题是默认情况下选择了我的段控件,但数据未填充 table 视图。尽管如此,我还是使用了段控制选择的方法
//ViewController
import UIKit
class MyOrdersVC: UIViewController {
//MARK: - IBOutlets
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var segmentedControl: UISegmentedControl!
//MARK: - Variables
var searchController = UISearchController()
// list all pagerlist
var totalOrders = [BookingMasterModel]() {
didSet {
tableView.reloadData()
}
}
var upcomingOrders = [BookingMasterModel]() {
didSet {
tableView.reloadData()
}
}
var completedOrders = [BookingMasterModel]() {
didSet {
tableView.reloadData()
}
}
var cancelledOrders = [BookingMasterModel]() {
didSet {
tableView.reloadData()
}
}
var arrFilter:[BookingMasterModel] = [] {
didSet{
tableView.reloadData()
}
}
//MARK: ViewController Life cycle
override func viewDidLoad() {
super.viewDidLoad()
// index = 0
segmentedControl.selectedSegmentIndex = 0
segmentedControl.setEnabled(true, forSegmentAt: 0)
segmentedControl.sendActions(for: .valueChanged)
//searchbar configuration
configureSearchController()
//By default Upcoming order is selected
callUpdatedOrders(totalOrders: totalOrders)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(false)
segmentedControl.selectedSegmentIndex = 0
callMyOrders()
}
//configure SearchViewController
func configureSearchController() {
self.searchController = ({
let controller = UISearchController(searchResultsController: nil)
controller.searchResultsUpdater = self
controller.dimsBackgroundDuringPresentation = true
controller.searchBar.sizeToFit()
controller.searchBar.placeholder = "Search by Receipt No, Order No"
controller.searchBar.showsCancelButton = false
controller.searchBar.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
controller.searchBar.searchBarStyle = .minimal
controller.searchBar.setShowsCancelButton(false, animated: false)
let textFieldInsideSearchBar = controller.searchBar.value(forKey: "searchField") as? UITextField
let imageView = textFieldInsideSearchBar?.leftView as! UIImageView
imageView.image = imageView.image?.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
imageView.tintColor = #colorLiteral(red: 0.8901960784, green: 0.1764705882, blue: 0.2156862745, alpha: 1)
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
imageView.isUserInteractionEnabled = true
imageView.addGestureRecognizer(tapGestureRecognizer)
//Add searchbar controller in header
self.tableView.tableHeaderView = controller.searchBar
return controller
})()
}
@objc func imageTapped(tapGestureRecognizer: UITapGestureRecognizer)
{
let tappedImage = tapGestureRecognizer.view as! UIImageView
print("Image tapped red")
// Your action
}
//MARK: - Button Action
@IBAction func segmentedControlAction(_ sender: Any) {
switch segmentedControl.selectedSegmentIndex {
case 0:
print("1")
callUpdatedOrders(totalOrders: totalOrders)
break
case 1:
print("2")
callCompletedOrders(totalOrders: totalOrders)
// tableView.reloadData()
// selectionFlag = 1
break
case 2:
print("3")
callCancelledOrders(totalOrders: totalOrders)
// tableView.reloadData()
// selectionFlag = 2
break
default:
print("Select proper segment")
callUpdatedOrders(totalOrders: totalOrders)
break
}
}
//MARK: - Arrays
func callUpdatedOrders(totalOrders : [BookingMasterModel]) {
upcomingOrders = totalOrders
upcomingOrders = upcomingOrders.filter { ([=12=].status != "CANCELLED") || [=12=].status != "REJECTED" || [=12=].status != "SERVICED" || [=12=].status != "DONE" || [=12=].status != "CREDITED" || [=12=].status != "DILEVERY" || [=12=].status != "REPORTED" || [=12=].status != "PARTIALY DONE" || [=12=].status != "DISPATCHED"}
}
func callCompletedOrders(totalOrders : [BookingMasterModel]) {
completedOrders = totalOrders
completedOrders = completedOrders.filter { [=12=].status == "SERVICED" || [=12=].status == "DONE" || [=12=].status == "CREDITED" || [=12=].status == "DILEVERY" || [=12=].status == "REPORTED" || [=12=].status == "PARTIALY DONE" || [=12=].status == "DISPATCHED" }
}
func callCancelledOrders(totalOrders : [BookingMasterModel]) {
cancelledOrders = totalOrders
cancelledOrders = cancelledOrders.filter { [=12=].status == "CANCELLED" || [=12=].status == "REJECTED" }
}
//MARK : - Webservices
//MARK: View Profile
func callMyOrders(){
let url = Utilities.stringToUrl(urlString: finalUrl)
WebService.requestServices(url: url, method: .get, parameters: [:], view: view, showLoaderFlag: true) { (json) in
let orderObj = MyOrderModels(fromJson: json)
guard let success = orderObj.response else {
return
}
if success == "SUCCESS" {
if let details = orderObj.bookingMasterModels {
for value in details {
self.totalOrders.append(value)
}
print("Total Orders:- \(self.totalOrders.count)")
}
self.tableView.reloadData()
}
}
}
}
extension MyOrdersVC : TableViewDelegateGroup {
//MARK: UITableViewDelegate
private func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
}
private func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 44
}
//MARK: UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//TODO: Switch
switch segmentedControl.selectedSegmentIndex {
case 0:
return searchController.isActive ? arrFilter.count : upcomingOrders.count
case 1:
return searchController.isActive ? arrFilter.count : completedOrders.count
case 2:
return searchController.isActive ? arrFilter.count : cancelledOrders.count
default:
break
}
return searchController.isActive ? arrFilter.count : upcomingOrders.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier:
MyOrdersTableViewCell.identifier, for: indexPath) as? MyOrdersTableViewCell{
//TODO: Switch
var order: BookingMasterModel?
switch segmentedControl.selectedSegmentIndex {
case 0:
order = searchController.isActive ? arrFilter[indexPath.row] : upcomingOrders[indexPath.row]
case 1:
order = searchController.isActive ? arrFilter[indexPath.row] : completedOrders[indexPath.row]
case 2:
order = searchController.isActive ? arrFilter[indexPath.row] : cancelledOrders[indexPath.row]
default:
order = searchController.isActive ? arrFilter[indexPath.row] : upcomingOrders[indexPath.row]
}
cell.orderDetails = order
cell.setOrders()
//Logic to display color background
var count : Int = 0
//suppose indexpath count exceeds to colorarray count then count = 32 /31 = 1 .... 2...
count = indexPath.row / colorArray.count
var x: Int = 0
x = indexPath.row - (count) * colorArray.count
cell.backgroundColor = colorArray[x]
return cell
}
return UITableViewCell()
}
}
extension MyOrdersVC : UISearchResultsUpdating,UISearchBarDelegate{
func updateSearchResults(for searchController: UISearchController) {
let searchText = searchController.searchBar.text ?? ""
switch segmentedControl.selectedSegmentIndex {
case 0:
arrFilter = upcomingOrders.filter { order in
let isMatchingSearchText = order.names.lowercased().contains(searchText.lowercased()) || searchText.lowercased().count == 0
return isMatchingSearchText
}
case 1:
arrFilter = completedOrders.filter { order in
let isMatchingSearchText = order.names.lowercased().contains(searchText.lowercased()) || searchText.lowercased().count == 0
return isMatchingSearchText
}
case 2:
arrFilter = cancelledOrders.filter { order in
let isMatchingSearchText = order.names.lowercased().contains(searchText.lowercased()) || searchText.lowercased().count == 0
return isMatchingSearchText
}
default:
break
}
}
private func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
searchBar.setShowsCancelButton(false, animated: false)
}
private func searchBarTextDidEndEditing(searchBar: UISearchBar) {
searchBar.setShowsCancelButton(false, animated: false)
}
}
在cell里面,我在做这个操作
import UIKit
class MyOrdersTableViewCell: UITableViewCell {
//MARK: IBOutlets
@IBOutlet weak var orderNo: UILabel!
@IBOutlet weak var apptDateLabel: UILabel!
//MARK: Variables
var orderDetails:BookingMasterModel?{
didSet{
setOrders()
}
}
class var identifier: String {
return String(describing: self)
}
class var nib: UINib {
return UINib(nibName: identifier, bundle: nil)
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
//MARK: Extra Function
//*******************
// function call when set ordres cell called
func setOrders(){
guard let txt = orderDetails?.names else {return}
self.orderNo.text = txt
}
}
问题是您在 UISegmentedControl
的操作中调用 callUpdatedOrders(totalOrders: totalOrders)
时您没有任何 totalOrders 因为您还没有数据。因此,如果您想在 ViewController
出现时显示数据,请调用 callMyOrders()
方法,并在此方法中在将订单附加到 totalOrders
[=26 后立即调用 callUpdatedOrders(totalOrders: totalOrders)
=]
if let details = orderObj.bookingMasterModels {
for value in details {
self.totalOrders.append(value)
}
print("Total Orders:- \(self.totalOrders.count)")
}
self.callUpdatedOrders(totalOrders: totalOrders)
备注:
- 您不必使用参数
totalOrders
调用函数callUpdatedOrders
, ... 因为totalOrders
是全局变量 - 对于
viewDidLoad
中的情况,您应该只调用super.viewDidLoad()
和configureSearchController()
- 在
callMyOrders()
的末尾你不必调用self.tableView.reloadData()
这是当你设置upcomingOrders
的值时调用
实际上,当您第一次在段控件中调用 callUpdateOrders 时,它不会在 updatingArray 中获取数据。所以按照罗伯特的建议在呼叫订单中称呼它。