I am using the below function to add buttons same like Fred and No in the next line but no getting same button size and text at same place.
- (IBAction)addAnotherBranchField:(id)sender
{
NSLog(#"Add Another Branch");
UIView *superview = self;
_buttons = [NSMutableArray array];
self.translatesAutoresizingMaskIntoConstraints = NO;
self.backgroundColor = [UIColor clearColor];
_verticalButtonConstraints = [NSMutableArray array];
NSString* previousAnswer = [_datasource valueForField:_field.guid branchIndex:0];
id buttonForLoadedAnswer = nil;
for (FormListOption* option in _field.options) {
UIButton* button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.translatesAutoresizingMaskIntoConstraints = NO;
//Add a little padding around the text - Using edge insets does not play well with the autolayout so do it with a space instead
[button setTitle:[NSString stringWithFormat:#" %# ",option.text] forState:UIControlStateNormal];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
[_buttons addObject:button];
[superview addSubview: button];
if ([option.text isEqualToString:previousAnswer]) {
buttonForLoadedAnswer = button;
}
}
paddingCounter = paddingCounter + 100;
UIButton *addButton = [[UIButton alloc] initWithFrame:CGRectMake(200, paddingCounter, 32, 32)];
[addButton setImage:[UIImage imageNamed:#"nav_newanswers.png"] forState:UIControlStateNormal];
[addButton addTarget:self action:#selector(addAnotherBranchField:) forControlEvents:UIControlEventTouchUpInside];
[superview addSubview:addButton];
[superview bringSubviewToFront:addButton];
//Add the constraints
NSMutableDictionary* views = [NSMutableDictionary dictionary];
NSMutableString* visualLayout = [NSMutableString stringWithString:#"H:|-(5)-"];
for (NSInteger i=0; i < [_buttons count]; i++) {
NSString* name = [NSString stringWithFormat:#"button_%d", i];
[views setValue:[_buttons objectAtIndex:i] forKey:name];
[visualLayout appendFormat:#"[%#(>=80)]-", name];
}
[visualLayout appendString:#"(>=10)-|"];
[superview addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:visualLayout
options:NSLayoutFormatAlignAllBottom
metrics:nil
views:views]];
}
- (void)updateVerticalConstrainsAgain:(UIView*)expandedView padding:(float)padding
{
[self removeConstraints:_verticalButtonConstraints];
[_verticalButtonConstraints removeAllObjects];
NSString* visualFormat = [NSString stringWithFormat: #"V:|[button]-(5)-%#|", expandedView ? [NSString stringWithFormat:#"[expanded]-(20)-"] : #""];
if (padding != 0 && expandedView == nil)
{
visualFormat = [NSString stringWithFormat:#"V:|[button(button)]-(%f)-|",padding];
}
for (UIView* button in _buttons) {
NSMutableDictionary* views = [NSMutableDictionary dictionaryWithObject:button forKey:#"button"];
if (expandedView) {
[views setObject:button forKey:#"expanded"];
}
NSArray* constraints = [NSLayoutConstraint constraintsWithVisualFormat:visualFormat
options:0
metrics:nil
views:views];
[self addConstraints:constraints];
[_verticalButtonConstraints addObjectsFromArray:constraints];
}
}
Please explain me whaere i am getting wrong. spend my full day to get out from problems.
Related
I have a UITableView that displays information but mostly the bit I am stuck on is showing star ratings. I have managed to create a custom UITableViewCell that contains the logic to display how man star rating each cell has. So if there is a rating of 3 it will display 3 yellow stars and 2 blank stars so altogether theres a total rating of 5. When the UITableView is displayed I can see that the star rating for the first 4 cells is correct:
Display of only TEN cells.
Rating in order of cell (what comes back from the Database):
5
3
3
1
0
0
0
0
0
0
but whats happening is that when I scroll the cells I get these ratings, seems to repeat the first for cell rating:
Rating in order of cell when scrolled (UI Scrolling):
5
3
3
1
5
3
3
1
5
3
Why is this happening?
I will give you code and edit if needed.
EDIT
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(tableView == tableViewTopThreads){
static NSString *simpleTableIdentifier = #"SimpleTableItem";
ThreadTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
//cell.layer.shouldRasterize = YES;
//cell.layer.rasterizationScale = [UIScreen mainScreen].scale;
if (cell == nil) {
cell = [[ThreadTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
Thread *t = (Thread*)[tmpArray4 objectAtIndex:indexPath.row];
cell.labelTitle.text = t.title;
cell.labelCat.text = t.cat;
cell.labelUser.text = [NSString stringWithFormat:#"%# %#", t.firstname, t.lastname];
cell.labelDate.text = [NSString stringWithFormat:#"%#", t.date];
cell.labelCountry.text = t.country;
cell.labelSubCat.text = t.subcat;
cell.rating = t.rating;
[cell.contentView setNeedsUpdateConstraints];
[cell.contentView updateConstraintsIfNeeded];
[cell.contentView setNeedsLayout];
[cell.contentView layoutIfNeeded];
return cell;
}
}
Custom Cell:
#import "ThreadTableViewCell.h"
#implementation ThreadTableViewCell
#synthesize main;
#synthesize top;
#synthesize center;
#synthesize bottom;
#synthesize rate;
#synthesize rating;
#synthesize labelTitle;
#synthesize labelCat;
#synthesize labelSubCat;
#synthesize labelUser;
#synthesize labelDate;
#synthesize labelCountry;
#synthesize imageviewThreadImage;
#synthesize imageviewRating1;
#synthesize imageviewRating2;
#synthesize imageviewRating3;
#synthesize imageviewRating4;
#synthesize imageviewRating5;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
//self.contentView.backgroundColor = [UIColor lightGrayColor];
[self.contentView setTranslatesAutoresizingMaskIntoConstraints:NO];
self.contentView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
//CGRect screenBound = [[UIScreen mainScreen] bounds];
//CGSize screenSize = screenBound.size;
//CGFloat screenWidth = screenSize.width;
//CGFloat screenHeight = screenSize.height;
main = [UIView new];
[self.contentView addSubview:main];
main.translatesAutoresizingMaskIntoConstraints = NO;
//[main sizeToFit];
main.backgroundColor = [UIColor whiteColor];
top = [UIView new];
[main addSubview:top];
top.translatesAutoresizingMaskIntoConstraints = NO;
//[top sizeToFit];
top.backgroundColor = [UIColor whiteColor];
labelUser = [UILabel new];
[top addSubview:labelUser];
labelUser.translatesAutoresizingMaskIntoConstraints = NO;
//[labelUser sizeToFit];
[labelUser setFont:[UIFont systemFontOfSize:14]];
labelUser.textColor = [UIColor colorWithRed:(114.0/255.0) green:(114.0/255.0) blue:(114.0/255.0) alpha:1.0];
labelDate = [UILabel new];
[top addSubview:labelDate];
labelDate.translatesAutoresizingMaskIntoConstraints = NO;
[labelDate sizeToFit];
[labelDate setFont:[UIFont systemFontOfSize:14]];
labelDate.textColor = [UIColor colorWithRed:(114.0/255.0) green:(114.0/255.0) blue:(114.0/255.0) alpha:1.0];
center = [UIView new];
[main addSubview:center];
center.translatesAutoresizingMaskIntoConstraints = NO;
[center sizeToFit];
center.backgroundColor = [UIColor whiteColor];
imageviewThreadImage = [UIImageView new];
[center addSubview:imageviewThreadImage];
imageviewThreadImage.translatesAutoresizingMaskIntoConstraints = NO;
imageviewThreadImage.backgroundColor = [UIColor colorWithRed:(207.0/255.0) green:(215.0/255.0) blue:(248.0/255.0) alpha:1.0];
labelTitle = [UILabel new];
[center addSubview:labelTitle];
labelTitle.translatesAutoresizingMaskIntoConstraints = NO;
[labelTitle sizeToFit];
labelTitle.lineBreakMode = NSLineBreakByWordWrapping;
[labelTitle setFont:[UIFont systemFontOfSize:14]];
labelTitle.textColor = [UIColor lightGrayColor];
labelTitle.numberOfLines = 0;
//labelTitle.preferredMaxLayoutWidth = screenWidth - 10 - 36;
bottom = [UIView new];
[main addSubview:bottom];
bottom.translatesAutoresizingMaskIntoConstraints = NO;
[bottom sizeToFit];
labelCat = [UILabel new];
[bottom addSubview:labelCat];
labelCat.translatesAutoresizingMaskIntoConstraints = NO;
[labelCat sizeToFit];
[labelCat setFont:[UIFont systemFontOfSize:12]];
labelCat.textColor = [UIColor colorWithRed:(58.0/255.0) green:(82.0/255.0) blue:(207.0/255.0) alpha:1.0];
labelSubCat = [UILabel new];
[bottom addSubview:labelSubCat];
labelSubCat.translatesAutoresizingMaskIntoConstraints = NO;
[labelSubCat sizeToFit];
[labelSubCat setFont:[UIFont systemFontOfSize:12]];
labelSubCat.textColor = [UIColor colorWithRed:(58.0/255.0) green:(82.0/255.0) blue:(207.0/255.0) alpha:1.0];
labelCountry = [UILabel new];
[bottom addSubview:labelCountry];
labelCountry.translatesAutoresizingMaskIntoConstraints = NO;
[labelCountry sizeToFit];
[labelCountry setFont:[UIFont systemFontOfSize:12]];
labelCountry.textColor = [UIColor colorWithRed:(58.0/255.0) green:(82.0/255.0) blue:(207.0/255.0) alpha:1.0];
rate = [UIView new];
[bottom addSubview:rate];
rate.translatesAutoresizingMaskIntoConstraints = NO;
[rate sizeToFit];
imageviewRating1 = [UIImageView new];
[rate addSubview:imageviewRating1];
imageviewRating1.translatesAutoresizingMaskIntoConstraints = NO;
[imageviewRating1 sizeToFit];
imageviewRating2 = [UIImageView new];
[rate addSubview:imageviewRating2];
imageviewRating2.translatesAutoresizingMaskIntoConstraints = NO;
[imageviewRating2 sizeToFit];
imageviewRating3 = [UIImageView new];
[rate addSubview:imageviewRating3];
imageviewRating3.translatesAutoresizingMaskIntoConstraints = NO;
[imageviewRating3 sizeToFit];
imageviewRating4 = [UIImageView new];
[rate addSubview:imageviewRating4];
imageviewRating4.translatesAutoresizingMaskIntoConstraints = NO;
[imageviewRating4 sizeToFit];
imageviewRating5 = [UIImageView new];
[rate addSubview:imageviewRating5];
imageviewRating5.translatesAutoresizingMaskIntoConstraints = NO;
[imageviewRating5 sizeToFit];
UIImage *imageStarDisabled = [UIImage imageNamed:#"star.png"];
//UIImage *imageStarEnabled = [UIImage imageNamed:#"star2.png"];
imageviewRating1.image = imageStarDisabled;
imageviewRating2.image = imageStarDisabled;
imageviewRating3.image = imageStarDisabled;
imageviewRating4.image = imageStarDisabled;
imageviewRating5.image = imageStarDisabled;
}
return self;
}
- (void)layoutSubviews
{
[super layoutSubviews];
// Make sure the contentView does a layout pass here so that its subviews have their frames set, which we
// need to use to set the preferredMaxLayoutWidth below.
[self.contentView setNeedsLayout];
[self.contentView layoutIfNeeded];
// Set the preferredMaxLayoutWidth of the mutli-line bodyLabel based on the evaluated width of the label's frame,
// as this will allow the text to wrap correctly, and as a result allow the label to take on the correct height.
self.labelTitle.preferredMaxLayoutWidth = CGRectGetWidth(self.labelTitle.frame);
}
- (void)updateConstraints {
[super updateConstraints];
if (self.didSetupConstraints) return;
//UIImage *imageStarDisabled = [UIImage imageNamed:#"star.png"];
UIImage *imageStarEnabled = [UIImage imageNamed:#"star2.png"];
if(rating > 0){
for(int i = 1; i < rating + 1; i++){
if(i == 1){
imageviewRating1.image = imageStarEnabled;
}
if (i == 2) {
imageviewRating2.image = imageStarEnabled;
}
if (i == 3) {
imageviewRating3.image = imageStarEnabled;
}
if (i == 4) {
imageviewRating4.image = imageStarEnabled;
}
if (i == 5) {
imageviewRating5.image = imageStarEnabled;
}
}
}
NSDictionary *viewsDictionary7 = #{#"main":main};
NSArray *constraint_H37 = [NSLayoutConstraint constraintsWithVisualFormat:#"V:|[main]|"
options:0
metrics:nil
views:viewsDictionary7];
NSArray *constraint_V37 = [NSLayoutConstraint constraintsWithVisualFormat:#"H:|[main]|"
options:0
metrics:nil
views:viewsDictionary7];
[self.contentView addConstraints:constraint_H37];
[self.contentView addConstraints:constraint_V37];
NSDictionary *viewsDictionary3 = #{#"top":top,#"center":center,#"bottom":bottom};
NSArray *constraint_H3 = [NSLayoutConstraint constraintsWithVisualFormat:#"V:|-5-[top]-5-[center]-5-[bottom]-10-|"
options:0
metrics:nil
views:viewsDictionary3];
NSArray *constraint_H33 = [NSLayoutConstraint constraintsWithVisualFormat:#"H:|[top]|"
options:0
metrics:nil
views:viewsDictionary3];
NSArray *constraint_H333 = [NSLayoutConstraint constraintsWithVisualFormat:#"H:|[center]|"
options:0
metrics:nil
views:viewsDictionary3];
NSArray *constraint_H3335657 = [NSLayoutConstraint constraintsWithVisualFormat:#"H:|[bottom]|"
options:0
metrics:nil
views:viewsDictionary3];
NSDictionary *viewsDictionary4 = #{#"labelUser":labelUser,#"labelDate":labelDate};
NSArray *constraint_H4 = [NSLayoutConstraint constraintsWithVisualFormat:#"V:|[labelUser]|"
options:0
metrics:nil
views:viewsDictionary4];
NSDictionary *viewsDictionary45 = #{#"labelDate":labelDate};
NSArray *constraint_H4555 = [NSLayoutConstraint constraintsWithVisualFormat:#"V:|[labelDate]|"
options:0
metrics:nil
views:viewsDictionary45];
NSArray *constraint_H44 = [NSLayoutConstraint constraintsWithVisualFormat:#"H:|-5-[labelUser]-20-[labelDate]-5-|"
options:0
metrics:nil
views:viewsDictionary4];
NSDictionary *viewsDictionary48 = #{#"labelTitle":labelTitle,#"imageviewThreadImage":imageviewThreadImage};
NSArray *constraint_H48 = [NSLayoutConstraint constraintsWithVisualFormat:#"V:|[labelTitle]|"
options:0
metrics:nil
views:viewsDictionary48];
NSArray *constraint_H48342 = [NSLayoutConstraint constraintsWithVisualFormat:#"V:|-8-[imageviewThreadImage(36)]|"
options:0
metrics:nil
views:viewsDictionary48];
NSArray *constraint_H448 = [NSLayoutConstraint constraintsWithVisualFormat:#"H:|-5-[imageviewThreadImage(36)]-5-[labelTitle]|"
options:0
metrics:nil
views:viewsDictionary48];
NSDictionary *viewsDictionary488 = #{#"labelCat":labelCat,#"labelCountry":labelCountry,#"labelSubCat":labelSubCat,#"rate":rate};
NSArray *constraint_H488 = [NSLayoutConstraint constraintsWithVisualFormat:#"V:|-5-[labelCat]|"
options:0
metrics:nil
views:viewsDictionary488];
NSArray *constraint_H48898 = [NSLayoutConstraint constraintsWithVisualFormat:#"V:|-5-[labelCountry]|"
options:0
metrics:nil
views:viewsDictionary488];
NSArray *constraint_H48898fgf54 = [NSLayoutConstraint constraintsWithVisualFormat:#"V:|-5-[labelSubCat]|"
options:0
metrics:nil
views:viewsDictionary488];
NSArray *constraint_H48898fgf54fdf = [NSLayoutConstraint constraintsWithVisualFormat:#"V:|-5-[rate]|"
options:0
metrics:nil
views:viewsDictionary488];
NSArray *constraint_H4488 = [NSLayoutConstraint constraintsWithVisualFormat:#"H:|-5-[labelCat]-10-[labelSubCat]-10-[labelCountry]-10-[rate]"
options:0
metrics:nil
views:viewsDictionary488];
NSDictionary *viewsDictionary4885 = #{#"imageviewRating1":imageviewRating1,#"imageviewRating2":imageviewRating2,#"imageviewRating3":imageviewRating3,#"imageviewRating4":imageviewRating4,#"imageviewRating5":imageviewRating5};
NSArray *constraint_H488fbfb = [NSLayoutConstraint constraintsWithVisualFormat:#"V:|[imageviewRating1(15)]|"
options:0
metrics:nil
views:viewsDictionary4885];
NSArray *constraint_H48898xfb = [NSLayoutConstraint constraintsWithVisualFormat:#"V:|[imageviewRating2(15)]|"
options:0
metrics:nil
views:viewsDictionary4885];
NSArray *constraint_H48898xfbfg = [NSLayoutConstraint constraintsWithVisualFormat:#"V:|[imageviewRating3(15)]|"
options:0
metrics:nil
views:viewsDictionary4885];
NSArray *constraint_H48898xfbxfg = [NSLayoutConstraint constraintsWithVisualFormat:#"V:|[imageviewRating4(15)]|"
options:0
metrics:nil
views:viewsDictionary4885];
NSArray *constraint_H48898xfrtbxfg = [NSLayoutConstraint constraintsWithVisualFormat:#"V:|[imageviewRating5(15)]|"
options:0
metrics:nil
views:viewsDictionary4885];
NSArray *constraint_H48898fgf54fxb = [NSLayoutConstraint constraintsWithVisualFormat:#"H:|[imageviewRating1(15)]-2-[imageviewRating2(15)]-2-[imageviewRating3(15)]-2-[imageviewRating4(15)]-2-[imageviewRating5(15)]"
options:0
metrics:nil
views:viewsDictionary4885];
[main addConstraints:constraint_H3];
[main addConstraints:constraint_H33];
[main addConstraints:constraint_H333];
[top addConstraints:constraint_H4];
[top addConstraints:constraint_H44];
[center addConstraints:constraint_H48];
[center addConstraints:constraint_H448];
[top addConstraints:constraint_H4555];
[main addConstraints:constraint_H3335657];
[main addConstraints:constraint_H488];
[main addConstraints:constraint_H4488];
[main addConstraints:constraint_H48898];
[main addConstraints:constraint_H48342];
[main addConstraints:constraint_H48898fgf54];
[main addConstraints:constraint_H48898fgf54fdf];
[bottom addConstraints:constraint_H488fbfb];
[bottom addConstraints:constraint_H48898xfb];
[bottom addConstraints:constraint_H48898xfbfg];
[bottom addConstraints:constraint_H48898xfbxfg];
[bottom addConstraints:constraint_H48898xfrtbxfg];
[bottom addConstraints:constraint_H48898fgf54fxb];
self.didSetupConstraints = YES;
}
- (void)awakeFromNib {
// Initialization code
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
#end
ViewController that sets the rating from the Database:
dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
// 3) Load picker in background
dispatch_async(concurrentQueue, ^{
NSString *myRequestString = [NSString stringWithFormat:#"threadTitle=%#&threadCountry=%#&threadCategory=%#&threadSubCategory=%#",searchThreadTitleTopThreads, searchThreadCountryTopThreads, searchThreadCategoryTopThreads, searchThreadSubCategoryTopThreads];
__block NSString *response = [self setupPhpCall:myRequestString :#"xxx.php"];
dispatch_async(dispatch_get_main_queue(), ^{
if(response.length > 0){
NSDictionary *dic = [response JSONValue];
if((NSNull*)dic != [NSNull null]){
int at_ID = 0;
int at_U_ID = 0;
int rating = 0;
NSString *at_Title;
NSString *at_Desc;
NSString *at_Cat;
NSString *at_SubCat;
NSString *at_Date;
NSString *at_Country;
NSString *at_FirstName;
NSString *at_LastName;
for(NSDictionary *dict in dic)
{
counter = counter + 1;
if((NSNull *)[dict objectForKey:#"AT_ID"] != [NSNull null]){
at_ID = [[dict objectForKey:#"AT_ID"] intValue];
}
if((NSNull *)[dict objectForKey:#"AT_U_ID"] != [NSNull null]){
at_U_ID = [[dict objectForKey:#"AT_U_ID"] intValue];
}
if((NSNull *)[dict objectForKey:#"AT_Title"] != [NSNull null]){
at_Title = [dict objectForKey:#"AT_Title"];
}
if((NSNull *)[dict objectForKey:#"AT_Desc"] != [NSNull null]){
at_Desc = [dict objectForKey:#"AT_Desc"];
}
if((NSNull *)[dict objectForKey:#"AT_Cat"] != [NSNull null]){
at_Cat = [dict objectForKey:#"AT_Cat"];
}
if((NSNull *)[dict objectForKey:#"AT_SubCat"] != [NSNull null]){
at_SubCat = [dict objectForKey:#"AT_SubCat"];
}
if((NSNull *)[dict objectForKey:#"AT_Country"] != [NSNull null]){
at_Country = [dict objectForKey:#"AT_Country"];
}
if((NSNull *)[dict objectForKey:#"U_FirstName"] != [NSNull null]){
at_FirstName = [dict objectForKey:#"U_FirstName"];
}
if((NSNull *)[dict objectForKey:#"U_LastName"] != [NSNull null]){
at_LastName = [dict objectForKey:#"U_LastName"];
}
if((NSNull *)[dict objectForKey:#"AVG(r.TR_Value)"] != [NSNull null]){
rating = [[dict objectForKey:#"AVG(r.TR_Value)"] intValue];
}
NSString *dateTS = [dict objectForKey:#"AT_Date"];
if((NSNull *)[dict objectForKey:#"AT_Date2"] != [NSNull null]){
NSString *timestampString = [dict objectForKey:#"AT_Date2"];
double timestampDate = [timestampString doubleValue];
NSDate *d = [NSDate dateWithTimeIntervalSince1970:timestampDate];
NSDateFormatter *_formatter=[[NSDateFormatter alloc]init];
[_formatter setDateFormat:#"dd.MM.yyyy HH:mm:ss"];
at_Date = [_formatter stringFromDate:d];
if (counter == 1) {
//lastDateForumActivity = dateTS;
}
}
if(counter == 1){
//lastDateForumActivity = dateTS;
}
Thread *thread = [[Thread alloc] init];
thread.tag = at_ID;
thread.idUser = at_U_ID;
thread.firstname = at_FirstName;
thread.lastname = at_LastName;
thread.idThread = at_ID;
thread.title = at_Title;
thread.desc = at_Desc;
thread.cat = at_Cat;
thread.date = at_Date;
thread.country = at_Country;
thread.subcat = at_SubCat;
thread.rating = rating; //RATING SET
[tmpArray4 addObject:thread];
//cell = nil;
}
at_ID = 0;
at_U_ID = 0;
at_Title = #"";
at_Desc = #"";
at_Cat = #"";
at_Date = #"";
at_Country = #"";
at_FirstName = #"";
at_LastName = #"";
}
}
You're problem is that you don't account for the cells being reused. Because the cells are reused, the initialization of the cells set the image to your disabled stars, but in your code to set the stars correctly, you only toggle them to the enabled star image. You never set them back if the current cell's rating is 0, but it is being applied to a reused cell that had a rating of 3. So your code will not change any of the images, so the 3 enabled star images will remain.
Add a setter for the rating property with something like this. Also, as of Xcode 4.4 or so, #synthesize isn't needed, so you can get rid of that.
- (void)setRating: (int)newRatingValue {
_rating = newRatingValue;
UIImage *imageStarDisabled = [UIImage imageNamed:#"star.png"];
UIImage *imageStarEnabled = [UIImage imageNamed:#"star2.png"];
imageviewRating1.image = rating >= 1 ? imageStarEnabled : imageStarDisabled;
imageviewRating2.image = rating >= 2 ? imageStarEnabled : imageStarDisabled;
imageviewRating3.image = rating >= 3 ? imageStarEnabled : imageStarDisabled;
imageviewRating4.image = rating >= 4 ? imageStarEnabled : imageStarDisabled;
imageviewRating5.image = rating >= 5 ? imageStarEnabled : imageStarDisabled;
}
I believe the below will work, although if you're updating the rating on the background thread, it may cause some problems. You may need to wrapp the updating of the images in a dispatch async call to execute it on the main (UI) thread like so:
dispatch_async( dispatch_get_main_queue(), ^{
imageviewRating1.image = rating >= 1 ? imageStarEnabled : imageStarDisabled;
imageviewRating2.image = rating >= 2 ? imageStarEnabled : imageStarDisabled;
imageviewRating3.image = rating >= 3 ? imageStarEnabled : imageStarDisabled;
imageviewRating4.image = rating >= 4 ? imageStarEnabled : imageStarDisabled;
imageviewRating5.image = rating >= 5 ? imageStarEnabled : imageStarDisabled;
});`
Also, you should learn how to use the debugger to put breakpoints and step through your code, inspecting the state of things. It will go a long way to helping to troubleshoot and diagnose these types of issues in the future.
I moved your logic here and worked #wottle:
if(tableView == tableViewTopThreads){
static NSString *simpleTableIdentifier = #"SimpleTableItem";
ThreadTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
//cell.layer.shouldRasterize = YES;
//cell.layer.rasterizationScale = [UIScreen mainScreen].scale;
if (cell == nil) {
cell = [[ThreadTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
Thread *t = (Thread*)[tmpArray4 objectAtIndex:indexPath.row];
cell.labelTitle.text = t.title;
cell.labelCat.text = t.cat;
cell.labelUser.text = [NSString stringWithFormat:#"%# %#", t.firstname, t.lastname];
cell.labelDate.text = [NSString stringWithFormat:#"%#", t.date];
cell.labelCountry.text = t.country;
cell.labelSubCat.text = t.subcat;
cell.rating = t.rating;
UIImage *imageStarDisabled = [UIImage imageNamed:#"star.png"];
UIImage *imageStarEnabled = [UIImage imageNamed:#"star2.png"];
cell.imageviewRating1.image = t.rating >= 1 ? imageStarEnabled : imageStarDisabled;
cell.imageviewRating2.image = t.rating >= 2 ? imageStarEnabled : imageStarDisabled;
cell.imageviewRating3.image = t.rating >= 3 ? imageStarEnabled : imageStarDisabled;
cell.imageviewRating4.image = t.rating >= 4 ? imageStarEnabled : imageStarDisabled;
cell.imageviewRating5.image = t.rating >= 5 ? imageStarEnabled : imageStarDisabled;
[cell.contentView setNeedsUpdateConstraints];
[cell.contentView updateConstraintsIfNeeded];
[cell.contentView setNeedsLayout];
[cell.contentView layoutIfNeeded];
return cell;
}
Is this the best place to put the logic?
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
How can I implement scroll view to horizontally scroll the view pages loaded from a NSDictionary. Presently i am using swipegesture but that is little slow.
What code should I implement to achieve horizontal scrolling?
i am using this code:
-(void)DownLoadData:(NSString *)indexSelect
{
{
[[SharedUtilities getInstance]AddActivityIndicatorViewOnMainThread:self.view];
}
self._parserForNewsDetail = [afaqsParser getInstance];
[[afaqsParser getInstance] setCacheNeed:TRUE];
[self._parserForNewsDetail parseWithUrl:[_arrUrlLinks objectAtIndex:[indexSelect integerValue]] UrlTypefor:nil];
NSDictionary *resultDic;
resultDic = [[[self._parserForNewsDetail getLinkAndIdDic] valueForKey:#"items"]objectAtIndex:0];
NSLog(#"Detail Dic = %#",[resultDic description]);
if (resultDic== NULL || resultDic ==nil)
{
//Check internet here
[[SharedUtilities getInstance]RemoveActivityIndicatorView];
[SharedUtilities ShowAlert:#"No Data Found" title:nil withView:self.view];
return;
}
[self performSelectorOnMainThread:#selector(SetValuesInUserInterface:) withObject: resultDic waitUntilDone:NO];
[[SharedUtilities getInstance]RemoveActivityIndicatorView];
}
-(void)SetValuesInUserInterface:(NSDictionary *)Dic
{
self._imageView1.layer.cornerRadius = 4;
self._imageView1.clipsToBounds = YES;
self._imageView1.tag = 999;
NSURL *imgurl =[NSURL URLWithString:[[Dic valueForKey:#"image"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
self._imageView1.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:imgurl]];
NSArray *subviewsArr = [self.view subviews];
for (int i=0; i<[subviewsArr count]; i++) {
if ([[subviewsArr objectAtIndex:i] isKindOfClass:[ImageDownLoader class]]) {
[[subviewsArr objectAtIndex:i] removeFromSuperview];
}
}
if ([[Dic valueForKey:#"image"] isEqual:#""])
{
// strg=[NSString stringWithFormat:#"%#, ",[Dic valueForKey:#"image"]];
_imageView1.hidden=YES;
// _txtView.frame=CGRectMake(4.0f,95.0f,310.0f,100.0f );
_txtView.frame=CGRectMake(4.0f,95.0f,_txtView.frame.size.width,_txtView.frame.size.height );
NSLog(#"NO IMAGE");
}
else{
_imageView1.hidden=NO;
_imageView1.frame=CGRectMake(4.0f,95.0f,310.0f,180.0f );
_txtView.frame=CGRectMake(4.0f,316.0f,_txtView.frame.size.width,_txtView.frame.size.height );
NSLog(#"IMAGE VISIBLE");
}
self._scrollView.scrollEnabled = YES;
self._scrollView.showsVerticalScrollIndicator = YES;
self._scrollView.showsHorizontalScrollIndicator = YES;
self._header.font = [UIFont fontWithName:#"HelveticaNeue-MediumCond" size:18];
[self._header setText: [Dic valueForKey:#"header"]];
self._header.textColor=[UIColor blackColor];
[self._publicationDate setText:[Dic valueForKey:#"PUB_DATE"]];
[self._kicker setText:[Dic valueForKey:#"kicker"]];
[self._txtView setText:[Dic valueForKey:#"ARTICLE_BODY"]];
NSString *writer;
if ([[Dic valueForKey:#"AUTHOR"] length]>2)
{
writer=[NSString stringWithFormat:#"%#, ",[Dic valueForKey:#"AUTHOR"]];
}
else
{
writer=#"";
}
NSString *city;
if ([[Dic valueForKey:#"REPORTING_CITY"] length]>2)
{
city=[NSString stringWithFormat:#", %#",[Dic valueForKey:#"REPORTING_CITY"]];
}
else
{
city=#"";
}
NSString *str = [NSString stringWithFormat:#"%#ee%#", writer,city];
//[cell._Writer setText: [tempDic valueForKey:#"writer"]];
[self._Writer setText:str];
[_txtView sizeToFit]; //added
[_txtView layoutIfNeeded]; //added
CGRect frame = self._txtView.frame;
self._txtView.frame = frame;
[_txtView setScrollEnabled:NO];
self._scrollView.contentSize = CGSizeMake(320,440+frame.size.height);
_titleLabel.frame= CGRectMake(0, self._scrollView.contentSize.height-119, [[UIScreen mainScreen] bounds].size.width, 40);
_titleLabel.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:1];
_titleLabel.textColor = [UIColor whiteColor];
_titleLabel.textAlignment = NSTextAlignmentCenter;
_titleLabel.font = [UIFont fontWithName:#"Helvetica" size:13.5];
_titleLabel.numberOfLines=2;
[self._scrollView addSubview:_titleLabel];
}
-(void)viewWillAppear:(BOOL)animated
{
self.navigationController.navigationBarHidden = YES;
}
- (void)viewDidLoad
{
[super viewDidLoad];
_titleLabel = [[UILabel alloc] init];
lblTitle.font = [UIFont fontWithName:#"HelveticaNeue-MediumCond" size:20];
lblTitle.text=_strTitle;
NSLog(#"arrUrls %d",[_arrUrlLinks count]);
NSLog(#"strCurrentNewsSelect %#",_strCurrentNewsSelect);
[[NSNotificationCenter defaultCenter]
postNotificationName:#"DISABLEGESTURE"
object:self];
count=[_strCurrentNewsSelect integerValue];
[self performSelectorInBackground:#selector(DownLoadData:) withObject:_strCurrentNewsSelect];
if([_strCurrentNewsSelect isEqualToString:#"0"])
{
btnPreviousNews.userInteractionEnabled=FALSE;
}
else{
}
_lblNewsCount.font = [UIFont fontWithName:#"HelveticaNeue-MediumCond" size:16];
_lblNewsCount.text=[NSString stringWithFormat:#"%d/%d",[_strCurrentNewsSelect integerValue]+1,[_arrUrlLinks count]];
// Do any additional setup after loading the view from its nib.
UIButton *shareBtn = [[UIButton alloc]initWithFrame:CGRectMake(280, 340, 40, 40)];
[shareBtn addTarget:self action:#selector(Share:) forControlEvents:UIControlEventTouchUpInside];
[shareBtn setBackgroundImage:[UIImage imageNamed:#"share1.png"] forState:UIControlStateNormal];
// [self.view addSubview:shareBtn];
if([_strCurrentNewsSelect isEqualToString:#"0"])
{
btnPreviousNews.userInteractionEnabled=FALSE;
[btnPreviousNews setImage:[UIImage imageNamed:#"arrow2_prev.png"] forState:UIControlStateNormal];
}
if([_strCurrentNewsSelect isEqualToString:[NSString stringWithFormat:#"%d",[_arrUrlLinks count]-1]])
{
btnNextNews.userInteractionEnabled=FALSE;
[btnNextNews setImage:[UIImage imageNamed:#"arrow2_next.png"] forState:UIControlStateNormal];
}
UISwipeGestureRecognizer *rightRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(rightSwipeHandle:)];
rightRecognizer.direction = UISwipeGestureRecognizerDirectionRight;
[rightRecognizer setNumberOfTouchesRequired:1];
//add the your gestureRecognizer , where to detect the touch..
[_scrollView addGestureRecognizer:rightRecognizer];
UISwipeGestureRecognizer *leftRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(leftSwipeHandle:)];
leftRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
[leftRecognizer setNumberOfTouchesRequired:1];
[_scrollView addGestureRecognizer:leftRecognizer];
}
- (void)rightSwipeHandle:(UISwipeGestureRecognizer*)gestureRecognizer
{
[self btnPreviousClick];
}
- (void)leftSwipeHandle:(UISwipeGestureRecognizer*)gestureRecognizer
{
NSLog(#"leftSwipeHandle");
[self btnNextClick];
}
-(IBAction)Share:(UIButton *)sender
{
NSLog(#"SHare called =%d",sender.tag);
// NSDictionary *tempDic = [[self._resultDic valueForKey:#"items"] objectAtIndex:sender.tag];
[[SharedUtilities getInstance] set_LinkForSharing:[[[[self._parserForNewsDetail getLinkAndIdDic] valueForKey:#"items"]objectAtIndex:0] valueForKey:#"image"]];
[[SharedUtilities getInstance]set_headerForSharing:[[[[self._parserForNewsDetail getLinkAndIdDic] valueForKey:#"items"]objectAtIndex:0] valueForKey:#"header"]];
[[SharedUtilities getInstance]set_viewController:self];
[[SharedUtilities getInstance]Share];
}
-(IBAction)btnBackPress:(id)sender;
{
[[NSNotificationCenter defaultCenter]
postNotificationName:#"ENABLEGESTURE"
object:self];
[self.navigationController popViewControllerAnimated:YES];
lblTitle.text=_strTitle;
}
-(IBAction)btnNextClick
{
btnPreviousNews.userInteractionEnabled=TRUE;
if(count!=[_arrUrlLinks count] -1)
{
if(count==[_arrUrlLinks count]-2)
{
btnNextNews.userInteractionEnabled=FALSE;
[btnNextNews setImage:[UIImage imageNamed:#"arrow2_next.png"] forState:UIControlStateNormal];
}
[btnPreviousNews setImage:[UIImage imageNamed:#"arrow1_prev.png"] forState:UIControlStateNormal];
count=count +1;
_lblNewsCount.text=[NSString stringWithFormat:#"%d/%d",count+1,[_arrUrlLinks count]];
NSLog(#"next %d",count);
[self performSelectorInBackground:#selector(DownLoadData:) withObject:[NSString stringWithFormat:#"%d",count]];
}
else{
btnNextNews.userInteractionEnabled=FALSE;
}
}
-(IBAction)btnPreviousClick
{
btnNextNews.userInteractionEnabled=TRUE;
if(count==0)
{
btnPreviousNews.userInteractionEnabled=FALSE;
}
else{
if(count==1)
{
[btnPreviousNews setImage:[UIImage imageNamed:#"arrow2_prev.png"] forState:UIControlStateNormal];
btnPreviousNews.userInteractionEnabled=FALSE;
}
[btnNextNews setImage:[UIImage imageNamed:#"arrow1_next.png"] forState:UIControlStateNormal];
count=count-1;
_lblNewsCount.text=[NSString stringWithFormat:#"%d/%d",count+1,[_arrUrlLinks count]];
NSLog(#"previous %d",count);
[self performSelectorInBackground:#selector(DownLoadData:) withObject:[NSString stringWithFormat:#"%d",count]];
}
}
}
Have you tried as like below methods,
UIScrollView * _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0, 10.0, 320.0, 280.0)];
_scrollView.backgroundColor = [UIColor clearColor];
_scrollView.pagingEnabled = YES;
_scrollView.showsHorizontalScrollIndicator = NO;
_scrollView.showsVerticalScrollIndicator = NO;
_scrollView.scrollsToTop = NO;
_scrollView.delegate = self;
[self addSubview:_scrollView];
float width = 0.0;
for (int i = 0; i < pageCount; i++)
{
UIView * yourView = [[UIView alloc] initWithFrame:CGRectMake((i * 320.0) + 20.0, 0.0, 280.0, 280.0);
[_scrollView addSubview:yourView];
width = yourView.frame.size.width + yourView.frame.origin.x + 20.0;
}
[_scrollView setContentSize:CGSizeMake(width, _scrollView.frame.size.height)];
Look at UIScrollView. To be honest this question makes it look like you've done very little research into the problem though. Can you tell us a bit more about what you currently have and what you've done so far?
UIScrollView Scroll depends on the ContentSize. So you have to set the ContentSize.
For Horizinatal Scrolling
[scroll setContentSize:CGSizeMake(1500, scroll.frame.size.height)];
Good afternoon. I use in my application iCarousel . At the moment I can not make Progress View each item carousel. The problem is that when I click on the "Download button" Progress View have added an item first . He appears fine and works , but also appears in another 2 item from another view, where it should not be . After that, when I again click the " download button " Progress View begin to be confused with each other. Please tell me exactly what I 'm doing wrong and how I act of intercourse ? I'm new to objective-c.
P.S To download the data I use AFNetworking.
iCarousel:
- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view
{
NSString *docDir = [NSHomeDirectory() stringByAppendingPathComponent:#"Library/Caches"];
NSDictionary *myDic =[magazinesInfo objectAtIndex:index];
//Change image size
UIImage *img = [UIImage imageWithImage:[UIImage imageWithContentsOfFile:[NSString stringWithFormat:#"%#/%#_img.png",docDir,[myDic objectForKey:#"title"]]] scaledToSize:CGSizeMake(370,513)];
UIImageView *faceImage = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,768,1004)];
UIImage *dwImage = [UIImage imageNamed:#"button.png"];
UIImage *readImage = [UIImage imageNamed:#"read_button.png"];
UIImage *deleteImage = [UIImage imageNamed:#"delete_button.png"];
UIImage *cancelImage = [UIImage imageNamed:#"cancelButton.png"];
if(view ==nil)
{
UILabel *nomer = [[UILabel alloc] initWithFrame:CGRectMake(345, 85+MY_OFFSET, 75, 29)];
UILabel *nameMag = [[UILabel alloc] initWithFrame:CGRectMake(55, 720+MY_OFFSET, 658, 80)];
UILabel *dateMag = [[UILabel alloc] initWithFrame:CGRectMake(55, 821+MY_OFFSET, 658, 23)];
UIButton *downloadButton = [[UIButton alloc] initWithFrame:CGRectMake(321, 890+MY_OFFSET, 128, 37)];
UIButton *readButton = [[UIButton alloc] initWithFrame:CGRectMake(246, 890+MY_OFFSET, 128, 37)];
UIButton *deleteButton = [[UIButton alloc] initWithFrame:CGRectMake(385, 890+MY_OFFSET, 128, 37)];
UIButton *cancelButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0+MY_OFFSET, 128, 37)];
view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 768, 1004)];
view = faceImage;
faceImage.image = nil;
((UIImageView *)view).image = nil;
view.contentMode = UIViewContentModeCenter;
//Magazine number
nomer.backgroundColor = [UIColor clearColor];
nomer.textAlignment = NSTextAlignmentCenter;
[nomer setFont:[UIFont fontWithName:#"OpenSans-Light" size:36.0f]];
nomer.textColor = [UIColor whiteColor];
nomer.tag = 1;
//Magazine name
nameMag.backgroundColor = [UIColor clearColor];
nameMag.textAlignment = NSTextAlignmentCenter;
[nameMag setFont:[UIFont fontWithName:#"OpenSans-Light" size:30.0f]];
nameMag.numberOfLines=2 ;
nameMag.textColor = [UIColor blackColor];
nameMag.tag = 3;
//Date magazine
dateMag.backgroundColor = [UIColor clearColor];
dateMag.textAlignment = NSTextAlignmentCenter;
[dateMag setFont:[UIFont fontWithName:#"OpenSans-Light" size:20.0f]];
dateMag.textColor = [UIColor blackColor];
dateMag.tag = 4;
//Download button
[downloadButton setBackgroundImage:dwImage forState:UIControlStateNormal];
[downloadButton addTarget:self action:#selector(pressDownload:) forControlEvents:UIControlEventTouchUpInside];
downloadButton.tag = 5;
downloadButton.hidden = YES;
//Read button
[readButton setBackgroundImage:readImage forState:UIControlStateNormal];
[readButton addTarget:self action:#selector(readMag:) forControlEvents:UIControlEventTouchUpInside];
readButton.hidden=YES;
readButton.tag = 8;
//Delete button
[deleteButton setBackgroundImage:deleteImage forState:UIControlStateNormal];
[deleteButton addTarget:self action:#selector(deleteMag:) forControlEvents:UIControlEventTouchUpInside];
deleteButton.hidden=YES;
deleteButton.tag = 9;
[cancelButton setBackgroundImage:cancelImage forState:UIControlStateNormal];
[cancelButton addTarget:self action:#selector(deleteMag:) forControlEvents:UIControlEventTouchUpInside];
cancelButton.hidden=NO;
cancelButton.tag = 10;
//Add label to view
[view addSubview:nomer];
[view addSubview:nameMag];
[view addSubview:dateMag];
//Add button to view
[view addSubview:downloadButton];
[view addSubview:readButton];
[view addSubview:deleteButton];
[view addSubview:cancelButton];
}
else
{
//Set tag to image
((UIImageView *)faceImage).image = (UIImage*)[view viewWithTag:2];
//Set tag to label
[[[view subviews]objectAtIndex:0]viewWithTag:1];
[[[view subviews]objectAtIndex:1]viewWithTag:3];
[[[view subviews]objectAtIndex:2]viewWithTag:4];
//Set tag to button
[[[view subviews]objectAtIndex:3]viewWithTag:5];
[[[view subviews]objectAtIndex:4]viewWithTag:8];
[[[view subviews]objectAtIndex:5]viewWithTag:9];
[[[view subviews]objectAtIndex:6]viewWithTag:10];
}
//Hide button download and show read,delete button
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:[NSString stringWithFormat:#"%#/%#_mag.pdf",docDir,[myDic objectForKey:#"title"]]] == YES)
{
[[[view subviews] objectAtIndex:4] setHidden:NO];
[[[view subviews] objectAtIndex:5] setHidden:NO];
[[[view subviews] objectAtIndex:3] setHidden:YES];
}
else
{
[[[view subviews] objectAtIndex:4] setHidden:YES];
[[[view subviews] objectAtIndex:5] setHidden:YES];
[[[view subviews] objectAtIndex:3] setHidden:NO];
}
//Hide date and name of magazine when view changed
if (index != [self.carousel currentItemIndex]) {
[[[view subviews]objectAtIndex:1]setHidden:YES];
[[[view subviews]objectAtIndex:2]setHidden:YES];
}
else{
[[[view subviews]objectAtIndex:1]setHidden:NO];
[[[view subviews]objectAtIndex:2]setHidden:NO];
}
((UIImageView *)view).image = img;
UILabel *nomer = [[view subviews]objectAtIndex:0];
nomer.text = [myDic objectForKey:#"title"];
UILabel *nameMag = [[view subviews]objectAtIndex:1];
nameMag.text = #"Жить интересно!” №5 Путешествия как стиль жизни";
UILabel *dateMag = [[view subviews]objectAtIndex:2];
dateMag.text = [myDic objectForKey:#"date"];
return view;
}
Download button action:
- (IBAction)pressDownload:(id)sender
{
NSLog(#"download button was pressed");
NSFileManager *fileManager = [NSFileManager defaultManager];
NSDictionary *myDic = [magazinesInfo objectAtIndex:curID];
NSString *docDir = [NSHomeDirectory() stringByAppendingPathComponent:#"Library/Caches"];
NSString *pdfFilePath = [NSString stringWithFormat:#"%#/%#_mag.pdf.tmp",docDir,[myDic objectForKey:#"title"]];
NSString *newPdfNamePath = [NSString stringWithFormat:#"%#/%#_mag.pdf",docDir,[myDic objectForKey:#"title"]];
//Test for Progress bar
UIButton *pressedButton = (UIButton *)sender;
UIView *superViewOfPressedButton = pressedButton.superview;
UIProgressView *downloadProgress = [[UIProgressView alloc] initWithFrame:CGRectMake(300, 950, 127, 8)];
UILabel *downloadPrecent = [[UILabel alloc]initWithFrame:CGRectMake(430, 950, 60, 20)];
[superViewOfPressedButton addSubview:downloadProgress];
[superViewOfPressedButton addSubview:downloadPrecent];
[downloadProgress setHidden:NO];
[downloadPrecent setHidden:NO];
NSLog(#"%#",sender);
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[myDic objectForKey:#"magazine"]]];
AFURLConnectionOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:pdfFilePath append:NO];
[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead)
{
downloadProgress.progress = (float)totalBytesRead / totalBytesExpectedToRead;
downloadPrecent.text =[NSString stringWithFormat:#"%1.0f%# ",((float)totalBytesRead / totalBytesExpectedToRead)*100,#"%"];
}];
[operation setCompletionBlock:^{
[fileManager moveItemAtPath:pdfFilePath toPath:newPdfNamePath error:NULL];
[fileManager removeItemAtPath:[NSString stringWithFormat:#"%#/%#_mag.pdf.tmp",docDir,[myDic objectForKey:#"title"]] error:NULL];
[downloadProgress setHidden:YES];
[downloadPrecent setHidden:YES];
NSLog(#"downloadComplete!");
[carousel reloadData];
}];
[operation start];
}
To Wain:
Sorry but I can not understand your question. I pass the URL from the dictionary in the method of downloading data. In Method iCarousel I assign Progress View tag = 7 then I add a condition to hide like this:
if (([fileManager fileExistsAtPath:[NSString stringWithFormat:#"%#/%#_mag.pdf.tmp",docDir,[myDic objectForKey:#"title"]]] == YES) && (index == [self.carousel currentItemIndex]))
{
[[[view viewWithTag:7] setHidden:NO];
[[[view viewWithTag:7] setHidden:NO];
}
else
{
[[[view viewWithTag:7] setHidden:YES];
[[[view viewWithTag:7] setHidden:YES];
}
Don't create and add the progress view in pressDownload:. Instead, create it when the view is created but set it to hidden. Then when you need it just un-hide it. When you reuse a view be sure to set the appropriate value based on whether you are downloading the item at that index.
In my quiz I have several answers. Correct answers are in plist.
here it is
<array>
<dict>
<key>QuestionTitle</key>
<string>Веки являются</string>
<key>Answers</key>
<array>
<string>частью глазного яблока</string>
<string>защитным аппаратом органа зрения</string>
<string>и тем, и другим</string>
<string>ни тем, ни другим</string>
</array>
<key>CorrectAnswer</key>
<array>
<integer>0</integer>
<integer>1</integer>
</array>
</dict>
Now I can't guess how to make check for answers that User answered
I may create variables 0,1,2,3 for A,B,C,D answers but how I should compare it with CorrectAnswer Array
There is my m. file code
NSString* path = [[NSBundle mainBundle] pathForResource:#"Questions2" ofType:#"plist"];
NSMutableArray *questionsDict = [[NSMutableArray alloc] initWithContentsOfFile:path];
NSUInteger count = [questionsDict count];
for (NSUInteger i = 0; i < count; ++i)
{
int nElements = count - i;
int n = (arc4random()% nElements) + i;
[questionsDict exchangeObjectAtIndex:i withObjectAtIndex:n];
}
self.questions = [questionsDict copy];
currentQuestion = 0;
NSDictionary* nextQuestion =
[self.questions objectAtIndex: currentQuestion];//[self.questions objectForKey:
[NSString stringWithFormat:#"%d", currentQuestion]];
NSMutableArray *array = [nextQuestion[#"Answers"] mutableCopy];
self.labelA.text = [array objectAtIndex:0];
self.labelB.text = [array objectAtIndex:1];
self.labelC.text = [array objectAtIndex:2];
self.labelD.text = [array objectAtIndex:3];
self.labelQuestion.text = [nextQuestion objectForKey:#"QuestionTitle"];
//Button D (A,B,C the same)
- (IBAction)fourButton:(id)sender
{
if (chekColorD == 0)
{
chekColorD++;
[buttonD setTitleColor:[UIColor yellowColor] forState:UIControlStateNormal];
//self.stringD = #"D";
}
else
{
chekColorD = 0;
[buttonD setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
// self.stringD = nil;
}
}
//NExt question button
- (IBAction)nextQuestion:(id)sender
{
// Тут делаешь сравнение правильных ответов
chekColorA = 0; chekColorB = 0; chekColorC = 0; chekColorD = 0;
[buttonA setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[buttonB setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[buttonC setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[buttonD setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
self.labelScore.text = [NSString stringWithFormat:#"%d", numCorrect];
if ([self.highScore integerForKey:#"HighScore"]<numCorrect){
[self.highScore setInteger:numCorrect forKey:#"HighScore"];
[self.highScore synchronize];
}
currentQuestion++;
if (currentQuestion <= [self.questions count]){
self.labelScore.text = [NSString stringWithFormat:#"%d", numCorrect];
self.labelHighestScore.text = [NSString stringWithFormat:#"%d",
[self.highScore integerForKey:#"HighScore"]];
NSDictionary* nextQuestion = [self.questions objectAtIndex: currentQuestion];
NSMutableArray *array = [nextQuestion[#"Answers"] mutableCopy];
self.labelA.text = [array objectAtIndex:0];
self.labelB.text = [array objectAtIndex:1];
self.labelC.text = [array objectAtIndex:2];
self.labelD.text = [array objectAtIndex:3];
self.labelQuestion.text = [nextQuestion objectForKey:#"QuestionTitle"];
//NSLog(#"%d количество вопросов", countQuestion);
}
else{
currentQuestion --;
}
}
You can compare two string like this:
if ([#"string1" isEqualToString:#"string2"]) {
// YES it s the same
}
else{
// no it s not the same
}
for example [labelA.text isEqualToString:correctAnswerString]. I recomend you to make buttons for answers: button1: firstAnswer, button2: secondAnswer and so on. When user tap on it, you can catch the sender which will be a UIButton, and if you set the button's title for the answer, you can compare the (UIButton*)sender.titleLabel.text isEqualToString:correctAnswer
// the question is: Lion is a...
UIButton* button1 = [[UIButton alloc] initWithFrame:CGRectMake(x, y, width, height)];
UIButton* button2 = [[UIButton alloc] initWithFrame:CGRectMake(x, y, width, height)];
UIButton* button3 = [[UIButton alloc] initWithFrame:CGRectMake(x, y, width, height)];
UIButton* button4 = [[UIButton alloc] initWithFrame:CGRectMake(x, y, width, height)];
[button1 setTitle:#"animal" forState:UIControlStateNormal];
[button2 setTitle:#"car" forState:UIControlStateNormal];
[button3 setTitle:#"tv" forState:UIControlStateNormal];
[button4 setTitle:#"radio station" forState:UIControlStateNormal];
[button1 addTarget:self action:#selector(checkAnswer:) forControlEvents:UIControlEventTouchUpInside];
[button2 addTarget:self action:#selector(checkAnswer:) forControlEvents:UIControlEventTouchUpInside];
[button3 addTarget:self action:#selector(checkAnswer:) forControlEvents:UIControlEventTouchUpInside];
[button4 addTarget:self action:#selector(checkAnswer:) forControlEvents:UIControlEventTouchUpInside];
-(bool) checkAnswer:(id)sender{
NSString* correctString = #"animal";
UIButton* tappedButton = (UIButton*)sender;
if ([tappedButton.titleLabel.text isEqualToString:correctString]) {
return YES;
}
return NO;
}
Goodevening
Although i've read quite a lot related questions about adding a UIButton to a UIScrollView it doesn't work for me. When i use UIImages instead of UIButtons it works like a charm. What am i missing here? (don't mind the if's or for-loops, al those are correct, paths of images also)
for(int j = 0; j < [subcategorie count]; j++){
NSArray *product = [subcategorie objectAtIndex:(j)];
int posX = 0;
for(int k = 1; k <= [product count]; k++){
if((i-1) == currentCategory ){
//NSString *fotoName = [NSString stringWithFormat:#"images/product/%#/%#_%i.png",self.categorieen[(i-1)] ,self.categorieen[(i-1)] , k];
NSString *fotoName = [NSString stringWithFormat:#"%#_%i",self.categorieen[(i-1)] , k];
NSString *currentCategory = [NSString stringWithFormat:#"images/product/%#/", self.categorieen[(i-1)]];
NSString *path = [[NSBundle mainBundle] pathForResource:fotoName ofType:#"png" inDirectory:currentCategory];
UIButton *fotoButton = [UIButton buttonWithType:UIButtonTypeCustom];
[fotoButton setImage:[UIImage imageNamed:path] forState:UIControlStateNormal];
fotoButton.frame = CGRectMake(posX, 252, 718, 520);
fotoButton.backgroundColor = [UIColor clearColor];
self.scrollview.contentSize = CGSizeMake(posX, 252);
[self.scrollview setBounces:YES];
[self.scrollview setPagingEnabled:YES];
[self.scrollview addSubview:fotoButton];
[self.scrollview bringSubviewToFront:fotoButton];
[self.scrollview setUserInteractionEnabled:YES];
self.scrollview.userInteractionEnabled = YES;
[self addSubview: self.scrollview];
posX += 718;
NSLog(#"Fotolink = %#", fotoName);
}
}
}
Cheers
[UIImage imageNamed:path] looks incorrect,
try [UIImage imageWithData:[NSData dataWithContentsOfFile:path]
UIButton *fotoButton = [UIButton buttonWithType:UIButtonTypeCustom];
[fotoButton setImage:[UIImage imageWithData:[NSData dataWithContentsOfFile:path] forState:UIControlStateNormal];