Struct check type | Swift - ios

Have the structure where contains 2 types - image and text. Have an array, where it will be added. How to make type check in cellForRowAtIndexPath?
struct typeArray {
var text: String?
var image: UIImage?
init(text: String){
self.text = text
}
init(image: UIImage){
self.image = image
}
}
var content = [AnyObject]()
Image add button:
let obj = typeArray(image: image)
content.append(obj.image!)
self.articleTableView.reloadData()
Text add button:
let obj = typeArray(text: self.articleTextView.text as String!)
self.content.append(obj.text!)
self.articleTableView.reloadData()
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
if content[indexPath.row] == {
let cell = self.articleTableView.dequeueReusableCellWithIdentifier("Text Cell", forIndexPath: indexPath) as! TextTableViewCell
cell.textArticle.text = content[indexPath.row] as? String
return cell
}
else if content[indexPath.row] == {
let cell = self.articleTableView.dequeueReusableCellWithIdentifier("Image Cell", forIndexPath: indexPath) as! ImageTableViewCell
cell.backgroundColor = UIColor.clearColor()
cell.imageArticle.image = content[indexPath.row] as? UIImage
return cell
}
return UITableViewCell()
}

You should declare your content array to hold instances of your typeArray struct;
var content = [typeArray]()
Then add instances of the struct to the array:
let obj = typeArray(image: image)
content.append(obj)
self.articleTableView.reloadData()
Then you can use this in your cellForRowAtIndexPath -
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let rowStruct = content[indexPath.row] {
if let text = rowStruct.text {
let cell = self.articleTableView.dequeueReusableCellWithIdentifier("Text Cell", forIndexPath: indexPath) as! TextTableViewCell
cell.textArticle.text = text
return cell
} else if let image = rowStruct.image {
let cell = self.articleTableView.dequeueReusableCellWithIdentifier("Image Cell", forIndexPath: indexPath) as! ImageTableViewCell
cell.backgroundColor = UIColor.clearColor()
cell.imageArticle.image = image
return cell
}
return UITableViewCell()
}

Related

Set the button image according to selection and default state

This is my code.
class NamePictureCell: UITableViewCell {
#IBOutlet weak var nameLabel: UILabel?
#IBOutlet weak var buttonType: UIButton?
func setOptions(Options1:NH_OptionsModel)
{
self.nameLabel?.text = Options1.values
}
// var item: NH_QuestionListModel? {
// didSet {
// self.nameLabel?.text = item?.buttontype
// }
// }
static var nib:UINib {
return UINib(nibName: identifier, bundle: nil)
}
static var identifier: String {
return String(describing: self)
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func prepareForReuse() {
super.prepareForReuse()
}
}
In viewController:-
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let model = questionViewModel.titleForHeaderInSection(atsection: indexPath.section)
// print(model.answerType?.hashValue)
print(model.answerType)
print(model.answerType?.rawValue)
switch model.answerType {
case .NHAnswerRadioButton?:
if let cell = self.tableview.dequeueReusableCell(withIdentifier: NamePictureCell.identifier) as? NamePictureCell {
// cell.item = model
cell.setOptions(Options1:questionViewModel.datafordisplay(atindex: indexPath))
// print(cell.item)
return cell
}
case .NHAnswerCheckboxButton?:
if let cell = self.tableview.dequeueReusableCell(withIdentifier: AboutCell.identifier, for: indexPath) as? AboutCell {
cell.setOptions(Options1:questionViewModel.datafordisplay(atindex: indexPath)) // cell.item = item
return cell
}
case .NHAnswerSmileyButton?:
if let cell = self.tableview.dequeueReusableCell(withIdentifier: FriendCell.identifier) as? FriendCell{
cell.textLabel?.text = ""
return cell
}
case .NHAnswerStarRatingButton?:
if let cell = self.tableview.dequeueReusableCell(withIdentifier: EmailCell.identifier) as? EmailCell {
cell.textLabel?.text = ""
return cell
}
case .NHAnswerTextButton?:
if let cell = self.tableview.dequeueReusableCell(withIdentifier:AttributeCell.identifier, for: indexPath) as? AttributeCell{
cell.textLabel?.text = ""
// cell.item = item
return cell
}
default:
return UITableViewCell()
}
return UITableViewCell()
}
And the model is :-
class NH_QuestionListModel: NSObject {
var dataListArray33:[NH_OptionsModel] = []
var id:Int!
var question:String!
var buttontype:String!
var options:[String]?
var v:String?
var answerType:NHAnswerType?
var optionsModelArray:[NH_OptionsModel] = []
init(dictionary :JSONDictionary) {
guard let question = dictionary["question"] as? String,
let typebutton = dictionary["button_type"] as? String,
let id = dictionary["id"] as? Int
else {
return
}
// (myString as NSString).integerValue
self.answerType = NHAnswerType(rawValue: Int(typebutton)!)
if let options = dictionary["options"] as? [String]{
print(options)
print(options)
for values in options{
print(values)
let optionmodel = NH_OptionsModel(values: values)
self.optionsModelArray.append(optionmodel)
}
}
self.buttontype = typebutton
self.question = question
self.id = id
}
}
In the tableview cell of the NamePictureCell, I have one label and one radio button.
In the xib of this cell. I set the following details for the button.
On default-One image given,
On Selected - another image given
So my question is according my api-
button type - 1 then at normal state the default image should display and on selecting the button the selected image should display.
How to do?
You can use following code to display default and selected button image :
buttonType.setImage(UIImage(named: "defaultImage")?.imageWithRenderingMode(.AlwaysOriginal), forState: .Normal)
buttonType.setImage(UIImage(named: "selectedImage")?.imageWithRenderingMode(.AlwaysOriginal), forState: .Highlighted)

How to display dynamically data from Server in CollectionViewCell in TableViewCell with swift3?

I got my json link data from TableViewCell , and then retrieve that data from server and display in collectionView with related TableViewCell data.
How to display this data in swift3? Please, help me.
I got url link (mainThemeList.main_associated_url,main_name) from TableViewCell.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let mainThemeList = mainHomeThemeTable[(indexPath as NSIndexPath).row]
let cell = tableView.dequeueReusableCell(withIdentifier: "homecell") as! HomeCategoryRowCell
DispatchQueue.main.async {
cell.categoryTitle.text = mainThemeList.main_name
cell.mainAssociatedURL.text = mainThemeList.main_associated_url
self.prefs.set(mainThemeList.main_name, forKey: "main_name")
cell.categoryTitle.font = UIFont.boldSystemFont(ofSize: 17.0)
cell.collectionView.reloadData()
}
DispatchQueue.main.async {
self.retrieveDataFromServer(associated_url: mainThemeList.main_associated_url,main_name: mainThemeList.main_name)
}
return cell
}
And then data related url link data from Server.
private func retrieveDataFromServe(associated_url : String , main_name: String) {
SwiftLoading().showLoading()
if Reachability().isInternetAvailable() == true {
self.rest.auth(auth: prefs.value(forKey: "access_token") as! String!)
rest.get(url: StringResource().mainURL + associated_url , parma: [ "show_min": "true" ], finished: {(result : NSDictionary, status : Int) -> Void in
self.assetsTable.removeAll()
if(status == 200){
let data = result["data"] as! NSArray
if (data.count>0){
for item in 0...(data.count) - 1 {
let themes : AnyObject = data[item] as AnyObject
let created = themes["created"] as! String
let assets_id = themes["id"] as! Int
let name = themes["name"] as! String
var poster_img_url = themes["poster_image_url"] as! String
let provider_id = themes["provider_id"] as! Int
poster_img_url = StringResource().posterURL + poster_img_url
self.assetsTable.append(AssetsTableItem(main_name: main_name,created: created,assets_id: assets_id, name: name, poster_image_url: poster_img_url,provider_id: provider_id))
}
}
SwiftLoading().hideLoading()
}else{
SwiftLoading().hideLoading()
}
})
}
}
Retrieve data from Server data store in assetsTable.
And then assetsTable data display in CollectionViewCell.
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "videoCell", for: indexPath) as! HomeVideoCell
cell.movieTitle.text = list.name
cell.imageView.image = list.image
return cell
}
My problem is collectionViewCell data are duplicate with previous assetsTable data and didn't show correct data in CollectionView.
My tableViewCell show (Action, Drama) label and My CollectionViewCell show movies Name and Movie Image. I retrieve data for CollectionViewCell from server but CollectionViewCell didn't display related data.
in HomeVideoCell Subclass clean up data in prepareforreuse
override func prepareForReuse() {
super.prepareForReuse()
self.movieTitle.text = ""
self.imageView.image = nil
}

Value comes as optional("myvalue"), how to get only value without the optional [duplicate]

This question already has answers here:
What is an optional value in Swift?
(15 answers)
Closed 5 years ago.
I am getting my value as Value comes as optional("myvalue"),But how can i get only value without the optional. I have tried a lot but not getting point, any help will be appreciated highly. The thing is that i am using Firebase as database and getting values in database.
I want to get value of Gender, Blood and country code.
Firebase connectivity
ref.child("user_registration").child(UserID!).setValue(["username": fullName.text!, "email": emailTextField.text!, "contact": numberText.text!, "city": myCity.text!, "state":countryText.text!, "gender": genderGroup, "blood": bloodGroup,"code": countryGroup])
Other code
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if tableView == tableViewB {
let cell = tableViewB.dequeueReusableCell(withIdentifier: "blood", for: indexPath)
cell.textLabel!.text = dropDownList[indexPath.row]
return cell
}
else if tableView == genderT {
let cell = genderT.dequeueReusableCell(withIdentifier: "gender", for: indexPath)
cell.textLabel!.text = genderL[indexPath.row]
return cell
}
else {
let cell = countryT.dequeueReusableCell(withIdentifier: "country", for: indexPath) as! CountryTableViewCell
cell.countryLabel.text = countryL[indexPath.row]
cell.flagImage.image = countryFlags[indexPath.row]
return cell
}
}
var bloodGroup : String?
var genderGroup : String?
var countryGroup : String?
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView == tableViewB {
let selectedData = dropDownList[indexPath.row]
buttonB.setTitle(selectedData, for: .normal)
self.tableViewB.isHidden = true
self.flag = 1
let indexPath = tableViewB.indexPathForSelectedRow
let currentCell = tableViewB.cellForRow(at: indexPath!)! as UITableViewCell
bloodGroup = currentCell.textLabel!.text!
print("\(bloodGroup)")
}
else if tableView == genderT {
let selectedDataG = genderL[indexPath.row]
genderB.setTitle(selectedDataG, for: .normal)
self.genderT.isHidden = true
self.flag = 1
let indexPath = genderT.indexPathForSelectedRow
let currentCell = genderT.cellForRow(at: indexPath!)! as UITableViewCell
genderGroup = currentCell.textLabel!.text!
print("\(genderGroup)")
}
else {
let selectedDataG = countryL[indexPath.row]
countryB.setTitle(selectedDataG, for: .normal)
self.countryT.isHidden = true
self.flag = 1
let indexPath = countryT.indexPathForSelectedRow
let currentCell = countryT.cellForRow(at: indexPath!)! as! CountryTableViewCell
countryGroup = currentCell.countryLabel.text!
let finalFlag = currentCell.flagImage.image!
print("\(finalFlag)" + "\(countryGroup)")
}
}
<br>
Console
com.apple.MobileAsset.TextInput.SpellChecker
Optional("male")
Optional("A+")
<UIImage: 0x600000295950>, {96, 64}Optional("+92")
fatal error: unexpectedly found nil while unwrapping an Optional value
Try this :
Print object
print(bloodGroup ?? "")
And
cell.textLabel!.text = (dropDownList[indexPath.row] ?? "")
Please write
if tableView == tableViewB {
let cell = tableViewB.dequeueReusableCell(withIdentifier: "blood", for: indexPath)
cell.textLabel!.text = dropDownList[indexPath.row] as! String
return cell
}
Instead of
if tableView == tableViewB {
let cell = tableViewB.dequeueReusableCell(withIdentifier: "blood", for: indexPath)
cell.textLabel!.text = dropDownList[indexPath.row]
return cell
}
In table view cellForRowAt method.

UIImage overlaps labels if it's set to .scaleAspectFill

My app loads images from a backend and displays them in a UITableViewCell, that contains a UIImageView to display it and some labels and buttons.
I've added the suggested contraints to the UITableViewCell with the 'Reset to suggested contraints' option.
Here's some of the code after retrieving the data:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = PostTableViewCell()
if (self.posts.count == 0) { return cell }
let post = posts[indexPath.row]
// Instancia o reuse identifier
if post["post_image"] != nil {
cell = tableView.dequeueReusableCell(withIdentifier: Storyboard.PostWithImage, for: indexPath) as! PostTableViewCell
} else {
cell = tableView.dequeueReusableCell(withIdentifier: Storyboard.PostWithoutImage, for: indexPath) as! PostTableViewCell
}
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
var cell = PostTableViewCell()
cell = tableView.dequeueReusableCell(withIdentifier: Storyboard.PostWithImage) as! PostTableViewCell
return cell.bounds.size.height;
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
var cell = PostTableViewCell()
cell = tableView.dequeueReusableCell(withIdentifier: Storyboard.PostWithImage) as! PostTableViewCell
return cell.bounds.size.height;
}
private func configureCell(cell: PostTableViewCell, atIndexPath indexPath: IndexPath) {
cell.queue.cancelAllOperations()
let operation: BlockOperation = BlockOperation()
operation.addExecutionBlock { [weak operation] () -> Void in
DispatchQueue.main.sync(execute: { [weak operation] () -> Void in
if (operation?.isCancelled)! { return }
let post = self.posts[indexPath.row]
cell.accessibilityIdentifier = post.recordID.recordName
guard let postTitle = post["post_title"], let postBody = post["post_body"] else {
return
}
if let asset = post["post_image"] as? CKAsset {
self.imageCache.queryDiskCache(forKey: post.recordID.recordName, done: { (image, cachetype) in
if image != nil {
cell.postImageView.contentMode = .scaleAspectFill
cell.postImageView.autoresizingMask = [.flexibleBottomMargin,
.flexibleHeight,
.flexibleLeftMargin,
.flexibleRightMargin,
.flexibleTopMargin,
.flexibleWidth ];
cell.postImageView.image = image!
} else {
do {
let data = try Data(contentsOf: asset.fileURL)
let image = UIImage(data: data)
cell.postImageView.contentMode = .scaleAspectFill
cell.postImageView.autoresizingMask = [.flexibleBottomMargin,
.flexibleHeight,
.flexibleLeftMargin,
.flexibleRightMargin,
.flexibleTopMargin,
.flexibleWidth ];
cell.postImageView.image = image!
self.imageCache.store(image!, forKey: post.recordID.recordName)
} catch {
print("Error 1001 = \(error.localizedDescription)")
}
}
})
}
cell.titleLabel.text = postTitle as? String
cell.bodyLabel.text = postBody as? String
})
}
cell.queue.addOperation(operation)
}
Here's some prints from the app itself that shows the image overlapping over the labels.
It only overlaps if the image is in portrait mode, if the image was taken in landscape it suits well.
What's the best way to bypass this issue?
You can programmatically tell the image to draw only in the given image area. If your constraints are working properly and it is staying the correct size, the image may just be drawing beyond the View bounds because of the .scaleAscpedtFill setting.
Do this by using .clipToBounds = true.
cell.postImageView.clipToBounds = true
Or, you can set it in interface builder as well, per the image below.
Give that a try and see if that helps?

UITableViewCell with two custom cells - Images keep changing

I am new to iOS programming. So sorry in advance in case my question sounds very naive. I have two custom cells in a UITableViewCell. One displaying images and labels and other displaying banner. I want to display labels with images in 3 cells and then show a banner and this continues.
Currently, I am able to display it as desired but when I scroll, images and banner change positions in cells.
Following is my code:-
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if VideosTableViewController.flag >= 1 {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CustomTableViewCell
let remoteImageUrlString = imageCollection[indexPath.row]
let imageUrl = NSURL(string:remoteImageUrlString)
let myBlock: SDWebImageCompletionBlock! = {(image:UIImage!, error: NSError!, cachetype:SDImageCacheType!, imageURL: NSURL!) -> Void in
}
//cell.myImageView?.image = nil
cell.myImageView.sd_setImageWithURL(imageUrl, completed: myBlock)
//set label
cell.myImageLabel.text = labelCollection[indexPath.row]
print(cell.myImageLabel?.text)
VideosTableViewController.flag = VideosTableViewController.flag - 1
return cell
}
else
{
let adCell = tableView.dequeueReusableCellWithIdentifier("adCell", forIndexPath: indexPath) as! VideosBannerAdCustomTableViewCell
VideosTableViewController.flag = VideosTableViewController.flag + 3
VideosTableViewController.flag = 3
adCell.videosBannerView.adUnitID = "banner id"
adCell.videosBannerView.rootViewController = self
let request : DFPRequest = DFPRequest()
//request.testDevices = [kGADSimulatorID]
request.testDevices = ["my test device id"]
adCell.videosBannerView.loadRequest(request)
return adCell
}
}
Try to use indexPath to determine which cell should be used. You are trying to display adCell with a banner in cell 4th, 8th, .... So it is very simple to be done by this:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.row % 4 != 0 || indexPath.row == 0 {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CustomTableViewCell
let remoteImageUrlString = imageCollection[indexPath.row]
let imageUrl = NSURL(string:remoteImageUrlString)
let myBlock: SDWebImageCompletionBlock! = {(image:UIImage!, error: NSError!, cachetype:SDImageCacheType!, imageURL: NSURL!) -> Void in
}
//cell.myImageView?.image = nil
cell.myImageView.sd_setImageWithURL(imageUrl, completed: myBlock)
//set label
cell.myImageLabel.text = labelCollection[indexPath.row]
print(cell.myImageLabel?.text)
VideosTableViewController.flag = VideosTableViewController.flag - 1
return cell
}
else
{
let adCell = tableView.dequeueReusableCellWithIdentifier("adCell", forIndexPath: indexPath) as! VideosBannerAdCustomTableViewCell
VideosTableViewController.flag = VideosTableViewController.flag + 3
VideosTableViewController.flag = 3
adCell.videosBannerView.adUnitID = "banner id"
adCell.videosBannerView.rootViewController = self
let request : DFPRequest = DFPRequest()
//request.testDevices = [kGADSimulatorID]
request.testDevices = ["my test device id"]
adCell.videosBannerView.loadRequest(request)
return adCell
}
}

Resources