質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
iOS

iOSとは、Apple製のスマートフォンであるiPhoneやタブレット端末のiPadに搭載しているオペレーションシステム(OS)です。その他にもiPod touch・Apple TVにも搭載されています。

Xcode

Xcodeはソフトウェア開発のための、Appleの統合開発環境です。Mac OSXに付随するかたちで配布されています。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

Q&A

解決済

1回答

13535閲覧

UITableViewのセクションヘッダー背景/文字色を変更したい。

Aki_1988

総合スコア44

iOS

iOSとは、Apple製のスマートフォンであるiPhoneやタブレット端末のiPadに搭載しているオペレーションシステム(OS)です。その他にもiPod touch・Apple TVにも搭載されています。

Xcode

Xcodeはソフトウェア開発のための、Appleの統合開発環境です。Mac OSXに付随するかたちで配布されています。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

0グッド

2クリップ

投稿2017/02/12 08:30

編集2017/02/12 10:15

###前提・実現したいこと
現在swiftを勉強中です。UITableViewでセクション分けとセクション部分のカスタマイズを行いたいのですが、具体的なやり方がわからず困っております。
具体的には、セクションの背景色と文字色を変更できればと考えております。
初歩的な質問かと思いますが、よろしくお願い致します。

イメージ説明

###試したこと
①セクションにlabelを設定して、それの背景色を設定する、を試しましたがこの関数では、Stringしか返せず。
返り値をUIViewにすると「objective-C method~」のようなエラー表示。

func tableView(tableView:UITableView, titleForHeaderInSection section:Int) -> String?{ let label = UILabel(frame: CGRect(x:0, y:0, width: tableView.bounds.width, height: 50)) label.text = taskSections[section] label.backgroundColor = UIColor.redColor() return label.text }

② @IBOutlet weak var taskList: UITableView!を行ったUITableViewのtableHeaderViewを設定しようとしたが、「EXC_BAD_INSTRUCTION」のエラーが発生。

let headerView = self.taskList.tableHeaderView as UIView! headerView.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 500) self.taskList.tableHeaderView = headerView

###ソース
回答頂いたものをもとに更新しております。

import UIKit class TaskListUITableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { override func viewDidLoad() { super.viewDidLoad() self.navigationItem.titleView = UIImageView(image:UIImage(named:"text_nav_title_today")) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //ストーリーボード連携 @IBOutlet weak var taskList: UITableView! //データ var taskTitles = [["task01","task02"],["task03"]] var taskSubTitles = [["subtask01","subtask02"],["subtask03"]] var taskSections:[String] = ["projectA","projectB"] //テーブル定義 func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return taskTitles[section].count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("TaskCell") as! TaskListTableCell var title = taskTitles[indexPath.section] var subtitle = taskSubTitles[indexPath.section] cell.setCell(title[indexPath.row], subTitle: subtitle[indexPath.row]) return cell } //section func tableView(tableView:UITableView, titleForHeaderInSection section:Int) -> String?{ return taskSections[section] } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return taskSections.count } // Section Header View func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { // HeaderのViewを作成してViewを返す let headerView = UIView() let label = UILabel() label.text = "セクション" label.textColor = UIColor.whiteColor() headerView.backgroundColor = UIColor.redColor() // いろいろ・・・ headerView.addSubview(label) return view } // Section Header Height func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { // ヘッダーViewの高さを返す return 40 } }

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

以下2つのUITableViewDelegateのメソッドを書きセクションヘッダーのViewを作成して返してください。
※ ラベルを載せて色を変える

swift

1// Section Header View 2func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { 3 // HeaderのViewを作成してViewを返す 4 let headerView = UIView() 5 let label = UILabel() 6 // いろいろ・・・ 7 8 headerView.addSubview(label) 9 return view 10} 11 12// Section Header Height 13func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { 14 // ヘッダーViewの高さを返す 15 return 40 16}

投稿2017/02/12 09:39

編集2017/02/12 12:40
_Kentarou

総合スコア8490

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

Aki_1988

2017/02/12 10:13 編集

回答ありがとうございます! ご指示いただいたやり方でやってみたのですが、上手くできず。先ほどのキャプと同じ画面が表示されております。(エラーは発生していないようです) おそらくどこかに誤りがまだあるのかと思います。大変恐縮ですが、再度ご教示いただけますでしょうか? 質問文のソースを更新しておりますので、ご確認お願い致します。
_Kentarou

2017/02/12 10:17

titleForHeaderInSectionのメソッドは消して大丈夫です。 今回追加したメソッドは呼ばれているでしょうか? tableView.delegate = self は設定していますか?
Aki_1988

2017/02/12 10:35

すいません、デリゲート抜けておりました。 しかし、デリゲートを追加したところ、「thread 1:signal SIGABRT」のエラーが発生してしまいました。。 デリゲートは以下を追加 ``` override func viewDidLoad() { super.viewDidLoad() self.navigationItem.titleView = UIImageView(image:UIImage(named:"text_nav_title_today")) taskList.delegate = self } ```
_Kentarou

2017/02/12 10:42

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { ViewControllerにプロトロルに準拠する記述はありますか?
Aki_1988

2017/02/12 10:45

記載しております。 関係ないかもしれませんが、swiftはVer2.2になっていました。そのあたり関係ありそうでしょうか?
_Kentarou

2017/02/12 10:52

それは関係ないと思います、コンソールにエラーメッセージがでていませんか? 出ている場合そちらを載せてください。
Aki_1988

2017/02/12 11:07

2017-02-12 19:59:51.396 bright[29783:305982] *** Terminating app due to uncaught exception 'CALayerInvalid', reason: 'layer <CALayer: 0x7fa8a9e9fc60> is a part of cycle in its layer tree' *** First throw call stack: ( 0 CoreFoundation 0x000000010c2e7d85 __exceptionPreprocess + 165 1 libobjc.A.dylib 0x000000010e757deb objc_exception_throw + 48 2 CoreFoundation 0x000000010c2e7cbd +[NSException raise:format:] + 205 3 QuartzCore 0x00000001137ed886 _ZN2CA5Layer30ensure_transaction_recursivelyEPNS_11TransactionE + 102 4 QuartzCore 0x00000001137ed8d1 _ZN2CA5Layer30ensure_transaction_recursivelyEPNS_11TransactionE + 177 5 QuartzCore 0x00000001137ed8d1 _ZN2CA5Layer30ensure_transaction_recursivelyEPNS_11TransactionE + 177 6 QuartzCore 0x00000001137f5891 _ZN2CA5Layer15insert_sublayerEPNS_11TransactionEP7CALayerm + 389 7 QuartzCore 0x00000001137f5db6 -[CALayer insertSublayer:below:] + 260 8 UIKit 0x000000010d292088 -[UIView(Internal) _addSubview:positioned:relativeTo:] + 1483 9 UIKit 0x000000010d303997 -[UITableView _addSubview:positioned:relativeTo:] + 76 10 UIKit 0x000000010d2ba87f -[UIScrollView(UIScrollViewInternal) _addContentSubview:atBack:] + 376 11 UIKit 0x000000010d30e453 -[UITableView _addContentSubview:atBack:] + 273 12 UIKit 0x000000010d30bb7b -[UITableView _updateVisibleHeadersAndFootersNow:] + 3143 13 UIKit 0x000000010d30d1d4 -[UITableView _updateVisibleCellsNow:isRecursive:] + 4153 14 UIKit 0x000000010d341686 -[UITableView _performWithCachedTraitCollection:] + 92 15 UIKit 0x000000010d328344 -[UITableView layoutSubviews] + 224 16 UIKit 0x000000010d295980 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 703 17 QuartzCore 0x00000001137fbc00 -[CALayer layoutSublayers] + 146 18 QuartzCore 0x00000001137f008e _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 366 19 QuartzCore 0x00000001137eff0c _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24 20 QuartzCore 0x00000001137e43c9 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 277 21 QuartzCore 0x0000000113812086 _ZN2CA11Transaction6commitEv + 486 22 QuartzCore 0x00000001138127f8 _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 92 23 CoreFoundation 0x000000010c20cc37 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23 24 CoreFoundation 0x000000010c20cba7 __CFRunLoopDoObservers + 391 25 CoreFoundation 0x000000010c20211c CFRunLoopRunSpecific + 524 26 UIKit 0x000000010d1d5f21 -[UIApplication _run] + 402 27 UIKit 0x000000010d1daf09 UIApplicationMain + 171 28 bright 0x000000010b68a0c2 main + 114 29 libdyld.dylib 0x000000010f3e792d start + 1 30 ??? 0x0000000000000001 0x0 + 1 ) libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)
Aki_1988

2017/02/12 11:08

こちらでよろしいでしょうか?
Aki_1988

2017/02/12 11:23 編集

すいません!上記ログ誤っておりました。再度アップ致します。お手数おかけしてすいません。
Aki_1988

2017/02/12 11:23

2017-02-12 20:18:36.204 bright[31926:320587] Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. ( "<_UILayoutSupportConstraint:0x7fef60e204d0 V:[_UILayoutGuide:0x7fef60e8d130(0)]>", "<_UILayoutSupportConstraint:0x7fef60e1f7b0 V:|-(0)-[_UILayoutGuide:0x7fef60e8d130] (Names: '|':UIView:0x7fef60e87800 )>", "<_UILayoutSupportConstraint:0x7fef60e7dcc0 V:[_UILayoutGuide:0x7fef60e8dc10(0)]>", "<_UILayoutSupportConstraint:0x7fef60e87180 _UILayoutGuide:0x7fef60e8dc10.bottom == UIView:0x7fef60e87800.bottom>", "<NSLayoutConstraint:0x7fef60e8cd40 V:[UIView:0x7fef60e87c30(44)]>", "<NSLayoutConstraint:0x7fef60e8e6b0 V:[_UILayoutGuide:0x7fef60e8d130]-(0)-[UIImageView:0x7fef60e87990]>", "<NSLayoutConstraint:0x7fef60e8e890 V:[UIImageView:0x7fef60e87990]-(0)-[UIView:0x7fef60e87c30]>", "<NSLayoutConstraint:0x7fef60e8e980 V:[UIView:0x7fef60e87c30]-(0)-[_UILayoutGuide:0x7fef60e8dc10]>", "<NSLayoutConstraint:0x7fef60e206d0 'UIView-Encapsulated-Layout-Height' V:[UIView:0x7fef60e87800(40)]>" ) Will attempt to recover by breaking constraint <NSLayoutConstraint:0x7fef60e8cd40 V:[UIView:0x7fef60e87c30(44)]> Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger. The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful. 2017-02-12 20:18:36.205 bright[31926:320587] Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. ( "<_UILayoutSupportConstraint:0x7fef60e204d0 V:[_UILayoutGuide:0x7fef60e8d130(0)]>", "<_UILayoutSupportConstraint:0x7fef60e1f7b0 V:|-(0)-[_UILayoutGuide:0x7fef60e8d130] (Names: '|':UIView:0x7fef60e87800 )>", "<_UILayoutSupportConstraint:0x7fef60e7dcc0 V:[_UILayoutGuide:0x7fef60e8dc10(0)]>", "<_UILayoutSupportConstraint:0x7fef60e87180 _UILayoutGuide:0x7fef60e8dc10.bottom == UIView:0x7fef60e87800.bottom>", "<NSLayoutConstraint:0x7fef60e8b5c0 V:[UIButton:0x7fef60e8b2b0'Button'(44)]>", "<NSLayoutConstraint:0x7fef60e8cf20 V:|-(0)-[UIButton:0x7fef60e8b2b0'Button'] (Names: '|':UIView:0x7fef60e87c30 )>", "<NSLayoutConstraint:0x7fef60e8e6b0 V:[_UILayoutGuide:0x7fef60e8d130]-(0)-[UIImageView:0x7fef60e87990]>", "<NSLayoutConstraint:0x7fef60e8e890 V:[UIImageView:0x7fef60e87990]-(0)-[UIView:0x7fef60e87c30]>", "<NSLayoutConstraint:0x7fef60e8e980 V:[UIView:0x7fef60e87c30]-(0)-[_UILayoutGuide:0x7fef60e8dc10]>", "<NSLayoutConstraint:0x7fef60e8cf70 V:[UIButton:0x7fef60e8b2b0'Button']-(0)-| (Names: '|':UIView:0x7fef60e87c30 )>", "<NSLayoutConstraint:0x7fef60e206d0 'UIView-Encapsulated-Layout-Height' V:[UIView:0x7fef60e87800(40)]>" ) Will attempt to recover by breaking constraint <NSLayoutConstraint:0x7fef60e8b5c0 V:[UIButton:0x7fef60e8b2b0'Button'(44)]> Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger. The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful. 2017-02-12 20:18:36.212 bright[31926:320587] *** Terminating app due to uncaught exception 'CALayerInvalid', reason: 'layer <CALayer: 0x7fef60e87970> is a part of cycle in its layer tree' *** First throw call stack: ( 0 CoreFoundation 0x0000000105da9d85 __exceptionPreprocess + 165 1 libobjc.A.dylib 0x0000000107b50deb objc_exception_throw + 48 2 CoreFoundation 0x0000000105da9cbd +[NSException raise:format:] + 205 3 QuartzCore 0x000000010d2af886 _ZN2CA5Layer30ensure_transaction_recursivelyEPNS_11TransactionE + 102 4 QuartzCore 0x000000010d2af8d1 _ZN2CA5Layer30ensure_transaction_recursivelyEPNS_11TransactionE + 177 5 QuartzCore 0x000000010d2af8d1 _ZN2CA5Layer30ensure_transaction_recursivelyEPNS_11TransactionE + 177 6 QuartzCore 0x000000010d2b7891 _ZN2CA5Layer15insert_sublayerEPNS_11TransactionEP7CALayerm + 389 7 QuartzCore 0x000000010d2b7db6 -[CALayer insertSublayer:below:] + 260 8 UIKit 0x000000010668b088 -[UIView(Internal) _addSubview:positioned:relativeTo:] + 1483 9 UIKit 0x00000001066fc997 -[UITableView _addSubview:positioned:relativeTo:] + 76 10 UIKit 0x00000001066b387f -[UIScrollView(UIScrollViewInternal) _addContentSubview:atBack:] + 376 11 UIKit 0x0000000106707453 -[UITableView _addContentSubview:atBack:] + 273 12 UIKit 0x0000000106704b7b -[UITableView _updateVisibleHeadersAndFootersNow:] + 3143 13 UIKit 0x00000001067061d4 -[UITableView _updateVisibleCellsNow:isRecursive:] + 4153 14 UIKit 0x000000010673a686 -[UITableView _performWithCachedTraitCollection:] + 92 15 UIKit 0x0000000106721344 -[UITableView layoutSubviews] + 224 16 UIKit 0x000000010668e980 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 703 17 QuartzCore 0x000000010d2bdc00 -[CALayer layoutSublayers] + 146 18 QuartzCore 0x000000010d2b208e _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 366 19 UIKit 0x000000010667e205 -[UIView(Hierarchy) layoutBelowIfNeeded] + 1129 20 UIKit 0x00000001067b35c5 -[UINavigationController _layoutViewController:] + 1613 21 UIKit 0x00000001067b23b4 -[UINavigationController _layoutTopViewController] + 268 22 UIKit 0x00000001067af6bd -[UINavigationController navigationTransitionView:didEndTransition:fromView:toView:] + 856 23 UIKit 0x0000000106a59c2c -[UINavigationTransitionView _notifyDelegateTransitionDidStopWithContext:] + 422 24 UIKit 0x0000000106a59fa2 -[UINavigationTransitionView _cleanupTransition] + 788 25 UIKit 0x00000001066617ff -[UIViewAnimationState sendDelegateAnimationDidStop:finished:] + 241 26 UIKit 0x000000010665e706 +[UIViewAnimationState popAnimationState] + 314 27 UIKit 0x0000000106a598dd -[UINavigationTransitionView transition:fromView:toView:] + 2640 28 UIKit 0x00000001067b4651 -[UINavigationController _startTransition:fromViewController:toViewController:] + 3291 29 UIKit 0x00000001067b4c4d -[UINavigationController _startDeferredTransitionIfNeeded:] + 890 30 UIKit 0x00000001067b5d0b -[UINavigationController __viewWillLayoutSubviews] + 57 31 UIKit 0x0000000106964503 -[UILayoutContainerView layoutSubviews] + 248 32 UIKit 0x000000010668e980 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 703 33 QuartzCore 0x000000010d2bdc00 -[CALayer layoutSublayers] + 146 34 QuartzCore 0x000000010d2b208e _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 366 35 QuartzCore 0x000000010d2b1f0c _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24 36 QuartzCore 0x000000010d2a63c9 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 277 37 QuartzCore 0x000000010d2d4086 _ZN2CA11Transaction6commitEv + 486 38 QuartzCore 0x000000010d2d47f8 _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 92 39 CoreFoundation 0x0000000105ccec37 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23 40 CoreFoundation 0x0000000105cceba7 __CFRunLoopDoObservers + 391 41 CoreFoundation 0x0000000105cc411c CFRunLoopRunSpecific + 524 42 UIKit 0x00000001065cef21 -[UIApplication _run] + 402 43 UIKit 0x00000001065d3f09 UIApplicationMain + 171 44 bright 0x00000001051522e2 main + 114 45 libdyld.dylib 0x00000001087e092d start + 1 46 ??? 0x0000000000000001 0x0 + 1 ) libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)
_Kentarou

2017/02/12 12:43

Swift2.2ということで一つ変わっている点がありました。回答を編集しましたが_アンダーバーがなくなっています。 そちらで試してみてください。
_Kentarou

2017/02/12 13:01

実際に同じようにプロジェクトを作ってみて原因が分かりました。 headerView.addSubview(label) return view セクションヘッダーのViewを返す部分でreturnしているのがself.viewになっています。 return headerView にしてください、こちらではこれで表示されました。
Aki_1988

2017/02/12 13:08

わー、すいません!できました! 何度もご確認いただきありがとうございました! 本当に助かりました!!
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問