2017-05-16 2 views
0

비슷한 질문을 읽었지만 답변을 얻지 못했습니다. 헤더가있는 표보기가 있으며 첫 번째 표제에는 제목과 숫자가 있습니다. 표보기의 머리글에서 그 번호의 색을 변경하고 싶습니다. 여기 있습니다 내 코드 : 내 코드에서 참조로신속한 3에서 tableView에서 머리글 제목 부분의 색상을 변경하는 방법은 무엇입니까?

var headerList = ["Account" , "Help" , "" ] 

override func viewDidLoad() { 
     super.viewDidLoad() 
self.headerList[0] = "Account \(userAccountMoney)" 

} 
    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { 

    let returnedView = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 25)) 
    returnedView.backgroundColor = UIColor.init(red: 229/255, green: 233/255, blue: 236/255, alpha: 1.0) 

    let label = UILabel(frame: CGRect(x: -20, y: 7, width: view.frame.size.width, height: 25)) 
    label.text = self.headerList[section] 
    label.textAlignment = .right 
    label.textColor = .lightGray 
} 

헤더 제목은 회색 그러나 나는 처음 헤더 제목에 계정 단어가 여전히 회색으로 원하는하지만 userAccountMoney는 문제가 그린 수 userAccountMoney 다른 변수이기 때문에 그 비슷한 질문을 사용할 수 없습니다.

+0

'NSAttributedString'을 만들고'attributedText' 속성을 사용하십시오. – vadian

+0

비슷한 질문을 읽었습니다.하지만 문제는 textColor를 변경하려고하지만 첫 번째 머리글 제목의 단어가 전부가 아닙니다. –

+0

NSAttributedString이 해결책입니다. . 내 대답을 보라. – vadian

답변

1

당신이 NS(Mutable)AttributedString를 사용에만 특정 범위에 색 속성을 추가 할 필요가 문자열의 일부의 색상 변경하려는 경우 :

if section == 0 { 
    let sectionTitle = self.headerList[0] 
    let attributedString = NSMutableAttributedString(string: sectionTitle) 
    if sectionTitle.characters.count > 8 { 
     attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: NSRange(location: 8, length: sectionTitle.characters.count - 8)) 
    } 
    label.attributedText = attributedString 
} else { 
    label.text = self.headerList[section] 
} 

는 인덱스 8입니다 "Account "


후 하드 코딩 된 인덱스 그러나 귀하의 경우에는 내가 작성하는 것이 좋습니다 것 headerList 상수

let headerList = ["" , "Help" , "" ] 

은 심지어 당신이 글꼴을 변경할 수 viewDidLoad의 코드를 삭제하고이 여러 색상의 텍스트를 만들 수 있습니다 NSAttributedString은 사용 계정 양을 동적으로

if section == 0 { 
    let attributedString = NSMutableAttributedString(string: "Account ") 
    attributedString.append(NSAttributedString(string: "\(userAccountMoney)", attributes: [NSForegroundColorAttributeName : UIColor.red])) 
    label.attributedText = attributedString 
} else { 
    label.text = self.headerList[section] 
} 
+0

이 코드를 사용할 때 오류가 발생합니다 –

+0

@SaeedRahmatolahi 어떤 오류가 있습니까? – vadian

+0

캐치되지 않은 예외 'NSRangeException'로 인해 앱 종료 중, 이유 : 'NSMutableRLEArray objectAtIndex : effectiveRange :: 경계에서 벗어남' *** 우선 스택 호출 : –

0

당신의 문제를 완전히 이해하지 못할 수도 있지만 diffe를 설정하고 싶습니다. 귀하의 첫 번째 tableview 헤더에 대한 임대 색상. section 변수에서 If-else 문을 사용하여이 작업을 수행하려고합니다. 마찬가지로 이

func setAttributedString(text string : String, subStringRange range : NSRange, subStringFont font1 : UIFont, mainStringFont font2 : UIFont, subStringColor color1 : UIColor = UIColor.gray, mainStringColor color2 : UIColor = UIColor.green) -> NSAttributedString { 

      let mainStringAttribute = [ NSFontAttributeName: font2, NSForegroundColorAttributeName : color2] as [String : Any] 
      let attributedString = NSMutableAttributedString(string: string, attributes: mainStringAttribute) 

      let subStringAttribute = [ NSFontAttributeName: font1, NSForegroundColorAttributeName : color1] as [String : Any] 
      attributedString.addAttributes(subStringAttribute, range: range) 

      return attributedString 
     } 

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { 

    if (section == 0) // this is first header 
    { 

    let returnedView = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 25)) 
    returnedView.backgroundColor = UIColor.init(red: 229/255, green: 233/255, blue: 236/255, alpha: 1.0) 

    let label = UILabel(frame: CGRect(x: -20, y: 7, width: view.frame.size.width, height: 25)) 
    label.text = self.headerList[section] 
    label.textAlignment = .right 
     let font1 = UIFont.systemFont(ofSize: 14.0) 
     let font2 = UIFont.systemFont(ofSize: 14.0) 

     label.attributedText = setAttributedString(text: "", subStringRange: NSRange(location: 0, length: 1), subStringFont: font1, mainStringFont: font2) 


    } 
    else /// remaining headers 
    { 

let returnedView = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 25)) 
    returnedView.backgroundColor = UIColor.init(red: 229/255, green: 233/255, blue: 236/255, alpha: 1.0) 

    let label = UILabel(frame: CGRect(x: -20, y: 7, width: view.frame.size.width, height: 25)) 
    label.text = self.headerList[section] 
    label.textAlignment = .right 
    label.textColor = .lightGray 
} 
} 
+0

나는 모든 텍스트를 변경하고 싶지 않다. 0 번 부분의 글자 색을 바꾼다. 나는 단지 텍스트를 바꾸고 싶다. 0 번 부분의 단어 중 하나를 색칠한다. –

+0

가 이제 확인해 보라. 문자열을 전달하고 텍스트의 범위를 변경하여 색상을 변경하는 새로운 방법을 추가했습니다.여전히 문제가있는 경우 알려주십시오 –

1

을 만들려면이 코드를 사용합니다. 다음 코드 조각은 다음과 같습니다

let titleAtt = NSAttributedString(string: "Hello", attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 18.0)!, NSForegroundColorAttributeName: UIColor.blue]) 
let numberAtt = NSAttributedString(string: "123", attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 18.0)!, NSForegroundColorAttributeName: UIColor.red]) 

let combinationAtt = NSMutableAttributedString() 
combinationAtt.append(titleAtt) 
combinationAtt.append(numberAtt) 
label.attributedText = combinationAtt 
0

당신은 코드를 아래와 같이 작성하여이를 달성 할 수있다 : 나는 모든 컨트롤러를 재사용 할 하나 개의 공통 기능을 만들었습니다

.

내가 좋아하는이 fuction를 사용하고
//MARK:- Set title with two different color 
func setTitle(title : String, loc : Int, len : Int) -> NSMutableAttributedString 
{ 
    let myMutableString = NSMutableAttributedString(
     string: title, 
     attributes: [:]) 

    myMutableString.addAttribute(
     NSForegroundColorAttributeName, 
     value: UIColor(red: 29/255, green: 140/255, blue: 242/255, alpha: 1.0), 
     range: NSRange(
      location:loc, 
      length:len)) 

    return myMutableString 
} 

, 동일한 컨트롤러를 들어

당신이 그것을 쓸 수

self.lblTitle.attributedText = self.setTitle(title: "My Profile", loc: 3, len: 7) 

또한 특정 문자의 색상을 변경하려면이 옵션을 사용할 수 있습니다. 문자열의 길이와 문자의 시작 위치를 지정해야합니다.

관련 문제