2014-11-16 1 views
0

UIButton의 발신자가 고유하지 않거나 변경되지 않는 이유가 궁금합니다. 각 셀의 단추가 동적으로 채워진 tableview (약 100 행) 있습니다. 모든 버튼은 동적이므로 다른 태그 ID를가집니다. 클릭 이벤트 함수에서 버튼을 변경하고 다른 것들을하고 싶습니다.Xcode6 swift UIButton 발신자가 고유하지 않습니까?

예를 들어 버튼 발신자를 사용하여 버튼을 식별하는 경우 색상이 변경되면 목록의 다른 버튼 하나가 변경됩니다.

스크롤하는 동안 발신자가 변경되는 것 같습니다. 모두 이상합니다.

미안합니다. 내가 놓치고있는 명백한 것들이 있다고 가정합니다. 여기

func followButtonTapped(sender: UIButton) { 
    println(sender) 
    println("UserID: \(sender.tag)") 
    sender.enabled = false 
    sender.backgroundColor = UIColor.grayColor() 
    sender.setTitle("...", forState: UIControlState.Normal) 
} 

예를 보낸 사람 : 여기

<UIButton: 0x7fe5249bacd0; frame = (297 17; 63 24); opaque = NO; autoresize = RM+BM; tag = 1147; layer = <CALayer: 0x7fe5249c2b10>> 
UserID: 1147 

내 cellForRowAtIndexPath

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ 

    tableView.tableFooterView = UIView(frame: CGRectZero) 
    tableView.estimatedRowHeight = 58 

    var cell : followCell! = tableView.dequeueReusableCellWithIdentifier(followCellIdentifier) as followCell! 

    if(cell == nil){ 
     cell = NSBundle.mainBundle().loadNibNamed(followCellIdentifier, owner: self, options: nil)[0] as followCell; 
    } 

    cell?.followName?.text=self.maintext[indexPath.row] 
    cell?.followSubtext?.text = self.subtext[indexPath.row] 
    cell?.followButton?.addTarget(self, action: "followButtonTapped:", forControlEvents: .TouchUpInside) 
    cell?.followButton?.tag = self.UserIds[indexPath.row].toInt()! 

    var image = UIImage(named: "default_avatar_40.jpg") 

    var imgURL: NSURL = NSURL(string: self.images[indexPath.row])! 
    let request: NSURLRequest = NSURLRequest(URL: imgURL) 
    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in 
     if error == nil { 
      var image = UIImage(data: data) 

      if let cellToUpdate = tableView.cellForRowAtIndexPath(indexPath) as? followCell { 
       cellToUpdate.followImage.image = image 
      } 
     } 
    }) 

    cell?.backgroundColor = UIColor.clearColor() 

    return cell as followCell 
} 

답변

1

나는 당신이 관찰하는 행동이있는 tableView 세포의 재사용으로 인해 믿습니다. 단추를 누른 다음 색상을 변경하면 해당 단추가 들어있는 셀은 화면 밖으로 스크롤 할 때까지 해당 표 행과 만 연관됩니다. 셀 (및 단추)은 화면에 표시되는 다른 행에 대해 재사용됩니다. cellForRowAtIndexPath에 색상을 다시 설정하지 않으면 화면에 나타나는 셀에 선택된 버튼이 표시 될 수 있습니다.

이 일을하려면, 당신은 3 일을해야합니다 버튼의

  1. 독립, 당신은 버튼을 모델 누르면되었는지 추적 할 필요가있다. 예를 들어,보기 컨트롤러 클래스에서 테이블의 각 단추에 대해 하나의 항목이있는 부울 배열을 사용합니다. cellForRowAtIndexPath에서

    var selected:[Bool] = Array(count: 100, repeatedValue: false) 
    
  2. 는 모델의 논리 값의 배열에 따라 버튼을 설정합니다.

    cellForRowAtIndexPathindexPath.row에있는 버튼의 태그를 설정할 수 있습니다, 버튼과 연관되어있는 줄 알고 다음 followButtonTappedsender.tag에 액세스 할 수 있습니다. followButtonTapped 변화가 선택되어있는 버튼에 대응하는 어레이에 부울

    cell.button.tag = indexPath.row 
    if selected[indexPath.row] { 
        cell.button.enabled = false 
        cell.button.backgroundColor = UIColor.grayColor() 
    } else { 
        cell.button.enabled = true 
        cell.button.backgroundColor = UIColor.whiteColor() 
    } 
    
  3. .

    func followButtonTapped(sender: UIButton) { 
        let row = sender.tag 
        selected[row] = true 
        println(sender) 
        println("UserID: \(sender.tag)") 
        sender.enabled = false 
        sender.backgroundColor = UIColor.grayColor() 
        sender.setTitle("...", forState: UIControlState.Normal) 
    } 
    
빠른 회신
+0

감사 @vacawama을,하지만 난이 일을하지 않습니다. 셀 식별자를 조작 할 수있는 방법이 있습니까? 방금 cellForRowAtIndexPath를 추가했습니다. – Norman

+0

테이블에 100 개의 행이 있지만 약 8 개의 셀만 할당됩니다. 화면을 스크롤하면 재사용 대기열에 넣어 재사용됩니다. 상태 데이터를 보유하기 위해 셀에 의존해서는 안됩니다. 모든 상태는 테이블 셀 외부에 있어야합니다. 이것이 내가'selected' 배열로 제안하려고했던 것입니다. – vacawama

관련 문제