使用按钮设置C​​ontentOffset

时间:2017-03-01 20:02:28

标签: ios objective-c button scrollview

我创建了一个带有几个按钮的.xib文件,并将其附加到inputAccessoryView。我使用scrollView可以滚动此部分,但是我必须使用按钮(箭头)添加其他功能。单击向前箭头它应该到达结尾,后退箭头将采用原始位置。

first position - start second position - end

我在没有任何代码的情况下在UI中创建了整个ScrollView。它运行良好,这些按钮位于此视图的顶部。我正在考虑使用这些按钮的IBAction并更改ContentOffSet。我正在努力实施。我会感激一些提示。

实施类:

#import "KCSearchInputAccessoryView.h"

 @implementation KCSearchInputAccessoryView

 + (KCSearchInputAccessoryView *)viewFromNib {
NSBundle *bundle = [NSBundle bundleForClass:[self class]];
return [[bundle loadNibNamed:NSStringFromClass([self class]) owner:nil options:nil] lastObject];
}

- (IBAction)backBtnTapped:(id)sender {

 }

 - (IBAction)forwardBtnTapped:(id)sender {

 }

 @end

1 个答案:

答案 0 :(得分:1)

您可以通过更改ContentOffset来实现,但是......

假设您有对按钮的引用,更好的方法可能是使用func scrollRectToVisible(_ rect: CGRect, animated: Bool)

IBAction func rightButton(sender: AnyObject) {
    self.theScrollView.scrollRectToVisible(postsButton.frame, animated: true)
}

IBAction func leftButton(sender: AnyObject) {
    self.theScrollView.scrollRectToVisible(chatsButton.frame, animated: true)
}

这也可以"滑动"横跨的按钮。

编辑:已经习惯了使用Swift的人...

Objective-C版本......而不是使用单独的Button框架,只需在滚动视图内容的开头或结尾创建一个rect:

- (IBAction)backBtnTapped:(id)sender {
    CGRect r = CGRectMake(0.0, 0.0, 1.0, 1.0);
    [_theScrollView scrollRectToVisible:r animated:YES];
}
- (IBAction)forwardBtnTapped:(id)sender {
    CGRect r = CGRectMake(_theScrollView.contentSize.width - 1, 0.0, 1.0, 1.0);
    [_theScrollView scrollRectToVisible:r animated:YES];
}

此处的示例项目:https://github.com/DonMag/ScratchPad