2017-03-05 1 views
0

외부 API로부터 사용자를 끌어 오는 '평가'기능을 내 앱에서 만드는 중입니다. 그런 다음 섹션 이름 (사용자 이름)과 UISlider가 포함 된 셀을 추가하는 TableView를 만듭니다.UserID와 함께 UISliders에서 값 가져 오기 (사용자를 섹션 번호로 연결)

내가하려는 일은 UISliders의 사용자 ID와 함께 사용자 데이터 섹션을 수집하여 API에 POST 작업을 호출하여 등급 데이터도 보낼 수 있도록하는 것입니다.

enter image description here

여기 내가 가지고있는 코드입니다 : (공식적으로, 스위프트와 처음으로, 코멘트 나이 작업을 수행하는 방법을 알아 내려고 노력하고있다). 어떤 아이디어?

import UIKit 
import Alamofire 


class RateViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { 

    @IBOutlet weak var submitButton: UIButton! 
    @IBOutlet weak var activeSurveyLabel: UILabel! 


    private var myTableView: UITableView! 
    var usersToRate = [User]() 
    var activeSurveyId: String? 
    var rateData = [String: Int]() 
    var sectionIdToUserId = [Int: String]() 
    var userIdSection = [Int: String]() 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     submitButton.isHidden = true 

     submitButton.addTarget(self, action: #selector(pressSubmitButton(button:)), for: UIControlEvents.touchUpInside) 

     activeSurveyLabel.isHidden = false 


     self.loadUsersToRate() 


     Alamofire.request(RateRouter.getSurvey()).responseJSON { response in 
      debugPrint(response) 


      if let string = response.result.value as? [[String: Any]]{ 

       if string.count == 0 { 
        return 
       } 

       self.submitButton.isHidden = false 
       self.activeSurveyLabel.isHidden = true 

       for survey in string { 
        if let survey = Survey(json: survey) { 
         self.activeSurveyId = survey._id! 
         print(survey._id!) 
        } 
       } 


       //if there's a result, show slider bars for each person on the team with rating scales (except for the person logged in) 
       //have a submit button with a post request for the votes 

       let barHeight: CGFloat = UIApplication.shared.statusBarFrame.size.height 
       let displayWidth: CGFloat = self.view.frame.width 
       let displayHeight: CGFloat = barHeight * CGFloat(self.usersToRate.count * 5) 

       self.myTableView = UITableView(frame: CGRect(x: 0, y: barHeight, width: displayWidth, height: displayHeight - barHeight)) 
       self.myTableView.register(UITableViewCell.self, forCellReuseIdentifier: "MyCell") 
       self.myTableView.dataSource = self 
       self.myTableView.delegate = self 
       self.view.addSubview(self.myTableView) 


      } else { 
       print(response.result.error!) 
       let label = UILabel() 
       label.center = self.view.center 
       label.text = "No Active Surveys" 
       self.view.addSubview(label) 
      } 

     } 




     // Do any additional setup after loading the view. 
    } 

    func loadUsersToRate() { 
     Alamofire.request(RateRouter.getUsers()).responseJSON { response in 
      guard let jsonArray = response.result.value as? [[String: Any]] else { 
       print("didn't get array, yo") 
       return 
      } 

      for item in jsonArray { 
       if let user = User(json: item) { 
        self.usersToRate.append(user) 

        self.rateData.updateValue(5, forKey: user.userId!) //initialize user average data at 5 in case they don't change it 
        print (self.rateData) 
       } 
      } 
     } 
    } 


    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
     print("Num: \(indexPath.row)") 
     print("Value: \(usersToRate[indexPath.row])") 

    } 

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return 1 
    } 


    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { 

     self.sectionIdToUserId.updateValue(usersToRate[section].userId!, forKey: section) 
     print(self.sectionIdToUserId) 
     return "\(usersToRate[section].name!)" 
    } 

    func numberOfSections(in tableView: UITableView) -> Int { 
     return usersToRate.count 
    } 

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath as IndexPath) 

     let slider = UISlider(frame: CGRect(x: 0, y:0, width: 400, height: 44)) 
     slider.isUserInteractionEnabled = true 
     slider.minimumValue = 1 
     slider.maximumValue = 10 
     slider.value = 5 
     slider.tag = indexPath.section 
     slider.addTarget(self, action: #selector(sliderValueChange(sender:)), for: UIControlEvents.valueChanged) 
     cell.addSubview(slider) 


     return cell 
    } 

    func sliderValueChange(sender: UISlider) { 
     //get slider value 
     var currentValue = Int(sender.value) 
     print(currentValue) 

     //self.rateData.updateValue(currentValue, forKey: self.sectionIdToUserId.values[sender.]) 



     //get user id for that value 
     //self.rateData.updateValue(currentValue, rateData[section]) 



     // self.rateData.updateValue(currentValue, forKey: 0) 
    } 

    func pressSubmitButton(button: UIButton) { 


     for user in usersToRate { 
      // Alamofire.request(RateRouter.vote(voteFor: user.userId!, survey: activeSurveyId, rating:)) 
     } 



    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 


    /* 
    // MARK: - Navigation 

    // In a storyboard-based application, you will often want to do a little preparation before navigation 
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
     // Get the new view controller using segue.destinationViewController. 
     // Pass the selected object to the new view controller. 
    } 
    */ 

} 

답변

0

내 자신의 질문에 대답하기 위해, 내가 한 것은 '투표'라는 다른 모델을 만들어 각 투표에 대한 정보를 저장했습니다.

다음 배열을 채우기 위해 섹션 ID를 기반으로 tableView에서 슬라이더에 대한 태그를 만들고이를 사용하여 현재 값을 업데이트했습니다.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath as IndexPath) 

    let slider = UISlider(frame: CGRect(x: 0, y:0, width: cell.frame.width , height: 44)) 

    slider.tag = indexPath.section 
    slider.addTarget(self, action: #selector(sliderValueChange(sender:)), for: UIControlEvents.valueChanged) 
    cell.addSubview(slider) 


    return cell 
} 

func sliderValueChange(sender: UISlider) { 
    //get slider value 
    var currentValue = Int(sender.value) 
    print(currentValue) 

    voteData[sender.tag].rating = currentValue 
}