Zhan Zhan - 1 month ago 9
iOS Question

How to display dynamic data in ViewController in Swift

In

Swift
I have
Realm DB
. And in my data base I have 10 items of data (news title) from server. Now I need display my data from
Realm DB
dynamical in
ViewController

I have function to display, but display only 1 data repeat in all 10 of news titles in
ViewController

I try display news title for each news with cycle, but not help.

Initialize

let realm = try! Realm()
let newsObj = realm.objects(News)


Function

func elementAtScrollViewIndex(index: Int) -> UIView {
let view = UIView(frame: CGRectMake(5.0, 0.0, 200.0, 200.0))
let image = UIImageView()
let imageLabel = UIImageView()
let newsLable = UILabel()

for indexes in newsObj {
newsLable.text = indexes.newsTitle
}

newsLable.lineBreakMode = .ByWordWrapping
newsLable.font = UIFont(name: "Roboto-Bold", size: 18)
newsLable.textColor = UIColor.whiteColor()
newsLable.frame = CGRectMake(7.0, 90.0, 200.0, 50.0)
newsLable.textAlignment = .Left
newsLable.numberOfLines = 0
imageLabel.backgroundColor = UIColor.blackColor()
imageLabel.alpha = 0.45
imageLabel.frame = CGRectMake(5.0, 90.0, 200.0, 65.0)
image.frame = view.frame
image.image = UIImage(named: "mechet")
view.addSubview(image)
view.addSubview(imageLabel)
view.addSubview(newsLable)

return view
}


enter image description here

Thank you for helping.

Answer

As per your code

for indexes in newsObj {
    newsLable.text = indexes.newsTitle
}

if you have 10 news in your newsObj till it display only 10th new text if you want to display 10 news then

write this

let indexes = newsObj[index]
newsLable.text = indexes.newsTitle

Remove this code

for indexes in newsObj {
newsLable.text = indexes.newsTitle
}